Microcontroller Decode
Microcontroller Decode
MICROCONTROLLER
(For END SEM Exam - 70 Marks)
• ( FEATURES ) •
�
� �"':':l.:x:::mi::1 :::::
( •May- 2018 •Aug. - 2018 . •Dec.· 2018 •May· 2019 t�
::i: ::::::�:«c-:�>
<«,><•W,<<0«c."M'- .__
, """>"<<"'<•""·--··...,...� .-.,.._,�,�--<"'-"">,..,,,...,,_,>.,,.m"'>"-""""""'''·>"�, X"'!•W«<"'<•..,..'-'"""'""'""'''"""""-'''"'
(i)
SYLLABUS
(304184)
A Gulde For Engineering Students
Microcontroller -
SUBJECT CODE: 304184 Unit III PIC 18F XXXX Microcontroller Architecture
PIC18FXXXX architecture with generalized block d\agram. MCU, Progrwn and Data
memory organization, Bank selection using Bank Select Register, Pin out diagram,
© Copyright with Technical Publications Reset operations, Watch Dog Timers, Configuration registers and oscillator options
All publishing rights (printed and ebook version) reserved with Technical Publications.
(CONFIG), Power down modes, Overview of instruction set. (Chapter - 4)
No port of this book should be reproduced in any form, Electronic, Mechanical, Photocopy
or any information storage and relrievol system without prior permission in writing,
from Technical Publications, Pun.e. Unit IV Peripheral Support in PIC 18FXXXX
Brief summary of Peripheral support, Timers and its Programing (mode 0 & 1 ) ,
Published by : Inten-upt Structun: of PIC18FXXXX with SFR, PORTB change Interrupts, use of
Amit Residency, Office No. l, 412, Shaniwar Peth,
( 't�®JECHNICA[® 0une - 411030, M.S. INDIA Ph.: +91-020-24495496/97 timer� with interrupts, CCP modes : Capture, Compare and PWM generation, DC
PUBLICATIONS Email : [email protected] .
An Up·Thrusl for Kno�ledge Motor speed control with CCP, Block diagram of in-built ADC with Control registers,
Website : www.technicalpublications.in
Sensor interfacing using ADC : All programs in embedded C. (Chapter - 5)
Printer:
Yogiraj Printers & Binders, Sr.No. 10/1 A,Ghule Industrial Estate, Nonded Villoge Reed, Unit V Real Word Interfacing With 18FXXXX
Tai. - Haveli, Dist. - Pune - 411041 .
Port structure with programming, Interfacing of LED, LCD and Key board, Motion
Detectors, Gas sensors, IR sensors, Design of PIC test Board and debugging,
MSSP structure (SPI & I2C), USART (Receiver and Transmitter), interfacing of RTC
78
-I. -
9 3 5 5 118 5 1 3 4 5 SPPU 19 '-
(DS1307) with I2C and EEPROM with SP!. Design of Traffic Light Controller; All
'.i r---����,,.,
'f
TABLE OF CONTENTS I
•,(\
i
��J
I 4 II
,,
. PIC 18FXXXX
Unit III .. . . Microcontroller Architecture
I
, ·')
Architecture (4 - 1) to (4 44)
-
Unit IV Harvard ·architecture and supports for RISC instruction set rather than
CISC. It is single chip microcontrollet developed by microchip and
Chapter - 5 Peripheral Support in PlC 18FXXXX (5 - 1) to (5 - 54) specifically used in embedded system development Most of the
·
PIC18FXXXX (7 - 1) to (7 52)
-
o I/O ports -- A, B, C, D, E
Q.2 Draw and explairi architecture of PIC 18FXXXX.
o ·Support devices such as timers/counters, ADC, USART etc.
ll<i" [SPPU: Dec-17, Marks 8, May-16, 15, 14, Marks 8)
Ans. : It is CMOS flash-based 8-bit microcontroller developed by
Microchip's and packed into 40 or 44-pin package and i.� upwards
compatible with the PIC16C5X, PIC12CXXX, PIC16CXX and
PIC l 7CXX with higher levels of hardware integration. It is high
performance, enhanced flash microcontrollers with CAN.. It uses
· Harvard architectlire with RISC instruction �et architecture. The
PIC l 8F4520 features a 'C' . compiler friendly development
environment, 256 bytes of EEPROM, self-programming, art ICD, 2
capture/compare/PWM functions, 8 channels of 10-bit Analog-to
Digital (AID) converter, the synchronous s�rial port can be configured
as either 3-wire Serial Peripheral Interface (SPI) or the 2-wire Inter
Integrated Circuit (r2C) bus and Addressable Universal Asynchronous
Receiver Transmitter (AUSART).
I
Microcontroller 4-4 PIC 18FXXXX Microco11troller Arcllitecture Microcontro/ler 4-5 PIC 1 BFXXXX Microcontroffer Arcftltecture
Sele�t Register (BSR). Data can be stored in the file register or required delay or due to watch dog timers. The instruction register
working register. The control unit synchronizes the operation provk� the code to fetch the data from data memory or file register.
I
of ALU while 21 bit program counter is used to access the The . PLL ci�cuit provides the option of mtdtiplying up the oscillator
2 Mbytes of ROM.
B. Program memory for instructions : 21 bit PC is used to
access the program ROM and stores the 16 bits of the
I ·frequency to speed up the overall operation. The watch dog timer can
be used to restart the· controller under program crash or uneven
execution of subroutines. The in-circuit ·debugger helps during
program development to diagnostic data and communicate to
instructions. In general instructions used by PIC l:l.re of 2 or
processor.
4 bytes long.
C. Data memory for data : The ma�hine code for a PIC18 Q.3 State features of the PIC 18FXXXX.
.
instruction has only 8 bits for a data memory address which
·
Qr [SPPU: May-22; Marks 6, May-17, Marks 3, In Sem: Aug.-16, Marks 5)
needs 12 bits. The Bank Select Register (BSR) supplies the Ans. : Features of PIC18FXX : The general features cf PIC
other 4 b.its. The total data memory is organized into 15 banks 18FXXX Microconttoller are as follows :
with each of 256 bytes storage capacity. Upper 128 bytes of
• Data Bus : 8-bit CPU With RISC architecture
bank 15 and lower 128 bytes of bank 0, are used as access
banks irrespective of bank selection. Data memory can be
• Clock : DC to 20 MHz
addressed directly or indirectly. • Instructions : 16 bits
D. 1/0 ports : 33 I/O lines amongst 5 ports: are used for •
.
Memory : 2 Mbytes of program ROM [21 Address line]
communication with outside environment. These ports are
· 4 kbytes of data RAM [12 Address lines]
A (6 - Bits), B, C and D (8 - Bits), E (3 - bits), they have direct
locatio
. ns in the memory as SFRS.
. 32 K flash ROM
1536 bytes SRAM - Scratch Pad
E. Support devices such as timers : Has four timers and PWM
mode working on 8 or 16 bit and used for the application as 256 bytes - EEPROM - For storing critical information
delay generation. • I/O Ports : 5 [A(6), B,C,D (8), E(3)] - 33 bidirecrional and
·
F. Support for serial communication: It has the USART port to individually addressable I/O lines.
receive and communicate the data serially. It is also supported • Timers : Five timers with 8 and 16-bit operation
by many other devices as 10 bit ADC, CCP modes and so on. • Has 15 bank registers with 256 entries
The ALU plays important role in functionii:ig of PIC, according to • Has GPR [variable] and SFR [fixed locations]. ·
Fig. Q.2.1,. The data from file register available in ROM is added with • Supports for USART operation
working register and may be stored in file or W register. The ;device • 10 bit, 8 channel ADC
can be reset by internal or external interrupt generated due to low • CCP modules..
voltage, in-sufficient clock, Power on reset circuit not providing 2
• 1 C/SPI serial port
,
•
operation
· and stores 16 bit result in product register pair( PRODH :
• Instruction decoder - when the instruction is fetched it goes into the ·
ID. '· .
PRODL) without affecting flags.
• The function of the ALU is shown in the Fig. Q.4.1. While • The CPU fetches instructions from memory, decodes them and
performing operation on ALU one of the operand is from. the · passes them to the ALU for execution.
program data memory multiplexed with other input fr�m SFRS and
. '
Ans. : Program Status Word (PSW) : Flags are 1-bit registers used ' Q.6 Explain data memory organization of PIC, comment on bank
to store the result of program. The Program Status Word (PSW) select register and access banks.
contains status bits tha.t reflect the current CPU state after arithmetic W [SPPU: Dec.-1.7, Marks 8, May-19, Marks 6, Nov.-15,
and logical operations. PIC has 5 math flags (N, OV, Z, DC, and C). May-16,17, Marks 8, In Sem: 16, Marks 5; April 12, 13]
The general structure of PSW is as shown in Fig. Q.S. l. Ans.: Data Memory Organization : The PIC 18F4550 has 4 KB of
data memory organized in 16 .banks, the banks are access by Bank
PSW Register of PIC
Select Regist�r (BSR) .. The data bus is. of 8 bit and will be stored in
87 86 BS 84 . 83 82 81 80
memory; as file register. The detailed data organization of data
memory is shown in fig. Q.6.1.
• Data memory up to 4 kbytes : Data register map - with 12-bit
address bus 000-FFF .:
Sign Zero
12
Digit carry
• Divided into 16 banks each of 256-byte (FFF = 2 = 16 x 256 =
4096 4 K)
=
operation is zero.
• In the core PIC18 instruction set, only the MOVFF instruction
• DC (Digit Curry flag) (Hal( Carry) : Set when carry generated fully specifies the 12-bit address of the source and target registers
from bit 3 to bit 4 in an arithmetic. operation. It is .used by BCD access bank.
arithmetic instructions.
• While the use of the BSR, with an embedded 8-bit address, allows
• C (Carry flag) : Set when an addition of unsigned number users to address the entire range of data memory, it also means that
generates a carry (ADDLW, ADDWF, SUBLW, apd SUBWF). the user must always ensure that the _correct bank is selected.
For subtraction operation polarity is reversed and performed by
o To streamline access for the most commonly used data memory
adding 2' s complement of second operand.
locations, the data memory is configured with an access bank,
which allows users to access a mapped block of memory
without specifying a BSR.
o The access bank is used by core PIC 18 instructions that include Accessing data memory
the a<;cess RAM bit (the "a" parameter in the instruction). • The machine code for a PIC 18 instruction has only 8 bits for a dat8:
o When "a = l ", the instruction uses the BSR and the 8-bit memory address which n�eds 12 bits. The Bank Select Register
address included in the opcode for the cata inemory address. (BSR) supplies the other 4 bits as shown in Fig. Q.6.2.
o When "a O'', the instruction is forced to use the access ·bank OxOO
=
PIC 18 instruction Ox7F
Bank 0
address map; the current value of the BSR is ignored entirely. Ox80
FFFh Ox FF
OxOO
� Bank 1
F80h Bank select register I OxFF
· F7Fr,
OxOO
FOOh Bank 2
EFFh
I/ ; . I
OxFF
OxOO
•
•
EOOh
Bank 15
DFF!1 OxFF
Access.bank
FFh Fig. Q.6.2 : Use of BSR for bank selection
DOOh
80h • Memory can be addressed directly and indirectly as shown in
?Fh Fig. Q.6.3 and Fig. Q.6.4.
2FFi: OOh
BSR<3:0> 7 ·From opcod1[3l O
256 Bytes
'
IW!l\i;j@W !I 1rnirn@l:iMf%!lWiil!iMM%lWN
� l Location select"�
'---
t
200h Bank select '
-
OOh 0111 OEh OFh
'iFFh
'IOOh •••
Data memo1y(1l
OFFh
080h
07Fh
Banko Bank 1 Ban:( 14 Bank 15
OOOh
Fig. Q.6.3 : Memory addressing
Fig. Q.6.1 : Data memory organization
Oh 11 6 7 0
,,,,4"y+·:rnf' h\t•'•**''''''' tn Ans. : Program Memory Organization
lr:struction \FSRnH I FSRnL )
:executed Localion select • PIC18 microcontrollers implement a '21-bit program counter,
:t:!fPfi��.?:��f t�:l:�faWK��t�$.$�lF! FFFh
_....y12 which is capable of addressing a 2-Mbyte program memory space.
l
i
?Jf:t)\F!ie address = :��1���i���a:�;�;
��ct Accessing INDFn/
I
Data rnemoty
'
Accessing a location between the· upper boundary of the physically
implemented memory and the 2-Mbyte address will return all 'O's
\!l*al:!'Wi®J1'12 ·12 (a NOP instruction).
I
Instruction! -:(S • PI Cl8 devices have two interrupt vectors. The Reset vector address
fetcr.ed 1
I@ PiMlW@tdfii:$1lM<# is at OOOO:H and the interrupt vector addresses are at 0008H and
oo.� SH as shown in Fig. Q.7.1.
Fig. Q.6.4 : Indirect addressing ·
• The 91h bit specifies either the access bank(= 0) or one ofthe banks
1. Computed GOTO, 2. Table Reads.
(= 1). • The Program Counter (PC) specifies the address of the instruction
to fetch for execution.
Data memory addressing - Indirect
• The PC is 21 bits wide and• is contained in three separate 8-bit
• 3 File Select Registers (FSR) as a pointer to the data memory
registers;
·
Q.7 Draw and explain the program memory map and stack of PIC
microcontroller.
� [SPPU: May-,2, Marks 6, In Sern: Aug-22, Marks 5, Apri\-12]
.,�.
PIC 18FXXXXMicroco11troller Arcllitecture Microco11/roller 4 - 15. PIC lBFXXXX Microco11troller Architecture
M/croco11troller 4 -14
T
components of general ·programming model are ALU, PSW, Pointers,
RAI\.1, Data and program ROM, Timers,, SFRS and ports as shown in
1
\
· Fig. Q. 8.1. It also represent the internal
microprocessor necessary to write assembly language programs. It has
architecture .of a
\\1t �/l
been divided into two groups as
MPlJ
i
..!.
'
F
Program mem.ory organization of PIC
'�� m)
Fig. Q.7.1 :
.. o
STACK : The stack operates as a 31-word by 21-bit RAM and a 5-bit 1 FF fa.:-;·.-;:1�:; Bc::rik
Ct)
Stack Pointer, STKPTR. The stack space is not part of either program 7F.
1)0
or data space. The stack organization is shown in Fig. Q.7.2. FF
e: l:O perts
Return address stack <20:0> J ii S:.:ppf;rt cievic%
'j
1 11 1 1
1 1 1 10
Stack pointer
Top-of-stack registers 1 1 1 01 ·
\. -..,.----)
. 00011 J Registers and Pointers
"-'C::: ....,... Top-of-stack
00010--
F•'j;<l"11'1"""'"·'"t''l 0000 1
" Working Register (W): 8 bit accumulator.
ocooo
• Program Counter (PC) : 21-bit register functions as a pointer to
Fig. Q.7.2: Stack indication
program �emory during program execution.
�
A Guide for E11gi11eeri11g St11de11ts � A Guide for E11gi11eeri11g Students
Microco11troller 4 - 16 PIC JBFXXXX Microco11troller Arcllitect11re Microco11troller 4 - 17 PIC 18FXXXX Microco11tro/ler Arcliitect11re
• Table Pointer : 21-bit register used as a memory pointer to copy Q.9 Enlist the steps in selection of PIC Microcontroller.
bytes between program ni.erriory and data registers.
Ans.: Seiection Criteria:
• Stack pointer (SP) : 5�bit register used to point to the stack. The selection of each microcontroller used for specific application
• Stack : 31 registers used for temporary storage of memory depends on following factors..
addresses during execution of a program. • Data handling capacity - Bits, Nibble bytes, words, double
• BSR: Bank Select Register (0 to F) : 4-bit register words, quad words etc ..
Provides upper 4-bits of 12-bit address of data memory. • Speed - depends on clock.
'
• FSR: File Select Registers: FSRO, FSRl and FSR2 • Amount of RAM/ ROM/ EPROM/ flash/ static.
FSR: Composed of two 8-bit registers: FSRH and FSRL • Number ofI/O pins, timers - All SFRS.
Used as pointers for data registers • Power consumption - Based on the modes.
Holds 12-bit address of data register • Pllckaging - 40 PIN DIP,/ QFP/ other - important - Space,
.,
interrupts, serial interface and ports. The location of each SFR is fixed SPI, I2C, USB.
and accessed by use of direct addressing mode. Data registers • Watchdog timer, Timer modes, data EEPROM �tc.
associated with 1/0 ports, support devices and . processes of data
· • Easy .to upgrade � Higher performances or · low power
transfer. operations.
• 1/0 Ports (A to E) • Interrupts
• EEPROM • Serial I/O Q.10 Draw the pin out diagram of PIC 18F4550 and explain
• Timers • Capture/Compare/PWM (CCP) function of each.
• . Analog-to-Digital (AID) converter Ans.: Pin Functions ofPIC 18F4550
Program and Data Memory • It uses the dual 'in-line package with forty pins as shown in
• Data memory up to 4 kbytes : Data register map - with 12-bit Fig. Q.1 o:i. The total forty pins and divided into different parts as
address bus 000-FFF. The total memory 1s divided into 16 banks port pins, reset, memory control and power supply; O,ut of 40 pins,
each of 256-byte (FFF = 212 = 16 x 256= 4096 = 4K) 33 pins are dedicated to 1/0 functions with five ports with alternate
functions. Rest of the pins are VDD, GND, OSCl, OSC2, a:nd
• PIC18 microcontrollers implement a 21-bit program counter,
which.is capable of addressing a 2-Mbyte program memory space. MCLR.
(a NOP instruction).
RE01f,N6IC.K1SPP - � R80!AN12!1NTO!FLTG/SDiiSDA
RE1iA.N5iCK2SPP ............. ....,............ V;;.::.:i
..,......:.,... -�··········V
Rt:·.2/AN7/0ESPP ss
Voo___.... ----.... HD7!SPP7iP� {)
'"SS__.... .,...__... f�!�i6JSPP!1fP·: C
\I
0$C11CLK; - F<D5!ilPP5lP111
OSC21CLKOtRAG - ..,..__,.,.. RD4/SPP4
RCO/T'l0SO/T13GJ<: ..,.__,,.... .,.._..,. RC7!RX!OT.!SDO
RESET
Q.11 Explain with block schematic function of RESET In PIC
18FXXXX.
Enebla l'='WRT
o MCLR reset during power-managed modes
Enoble OST(l)
'•
o The detailed combination of reset operation along with Device reset events are tracked through the RCON register as shown
functional diagram is shown in Fig. Q.11.1. in Fig. Q.11.2. The lower five bits of the re&ister indicate tr,1t a
specific reset event has occurred. In most cases, th�se bits can only be
cleared by the event and must be set by the application after the event.
The state of these flag bits, taken together, can be read to indicate the
type of Reset that just occurred. The RCON register also has control
bits for setting interrupt priority (IPEN) and software control of the
BOR (SBOREN).
A. Power-on Reset (POR) • Rl 2:: 1 k.'1 will limit any current flowing into MCLR from external
capacitor C, in the event of MCLR/VPP pin breakdown, due to
• A Power-on Reset pulse is generated on-chip when VDD rise is
Electro - Static Discharge (ESD) orElectrical Overstress (EOS). ·
detected above threshold. The power on circuit is shown in
.
Fig. Q.12.1. B. Power-up Timer (PWRT)
• To take advantage. of the POR circuitry, just tie. the MCLR pin • The power-up timer provides ·a fixed -nominal· time-out only on
directly (or through a resistor of 1 kn. to 10 kn) to VDD. This will power-up from the POR. The power-up timer operates on an
eliminate external RC components usually needed to create a internal RC oscillator.
power-on reset delay. • The chip is kept in RESET as long as the PWRT is active.
• A configuration bit is provided to enable/disable the PWRTEN. will reset the device. A reset may or may not occur if VDD falls
• The power-up time delay will vary from chip-to-chip due to VDD, below VBOR for less than threshold. The chip will remain in
· temperature and process variation. Brown-out Reset until VDD rises above VBOR.
• The Oscillator Start-up Timer (OST) provides a 1024 oscillator o Overcon:ie the fluctuations in VDD brown on reset voltage
cycle (from OSCl input) delay after the PWRT delay is over. provided.
Vdd
• This ensures that the crystal oscillator or resonator has started and.
·
. .
stabilized.
·
Vdd
Vdd
• The Oscillator Start-up Timer (OST) provides a 1024 oscillator
9ycle (from OSCl input) delay after the PWRT delay is over.
• This ensures that the crystal oscillator or resonator has started and·
0.5 Vdd
stabilized. ·· RS1'
• SOFTWARE ENABLED BOR: When BORENl;:BORENO =·01, . • The WDT and post scaler are cleared when any of the following
the BOR can be enabled or disabled by the user in software. This is events occur : a SLEEP or CLRWDT instruction is exec.uted, the
·
done with the control bit, SB OREN (RCON<6> ). Setting IRCF bits (OSCCON<6:4>) are changed or a clock failure has
·
SBOREN enables the BOR to function as previously described. occurred according to oscillator control bits.
Clearing SBOREN disables the BOR entirely. The SBOREN bit • The general block diagram of Watchdog timer is shown in
operates only in this mode; otherwise, it is read as 'O'. Fig� Q.13.1.
• Hardware BOR : When BOREN!: BORENO = 10, the BOR SWDTE.N�
· F..r:3bia'NDT .
INTRC counter
WOTEN-- ,
remains · under hardware control and operates as previously !
\..� · ···-
r ;=o--- �\�������:d
WOT coi.1nte.r
described. Whenever the device enters sleep mode, however, the ...
INTRG s�urcr:
BOR is automatically disabled.
Change on IRCF biis ·
• When the device returns to any other operating mode, BOR is CLRWOT
Reseti WDT
�i:?set
automatically re-enabled.
--·----------,,."'--·�·---.
t,
Note : BOR and the Power-on Timer (PWRI) are independently WDTPS•:3.0>
configured. Enabling BOR reset does not automatically enable the SLEEP �-�--� ·---- --'
!
PWRT. Fig. Q.13.1 Watchdog timer
Also the SFRS used for enabling the Watch<log timer are,
Q.13 Explain watch dog timer mode of RESET in PIC 18FXXXX.
source. ·
• The nominal wpT period is 4 ms and has the same stability as the Bit 0 SWDTEN : Software controlled Watchdog timer Enable bit :
INTRC oscillator. The period of the WDT is multiplied by a 16-bit This bit has no effect if the .:onfiguration bit, WDTEN, is enabled in
postscaler. CONFIG 2H register
"'.:�®
!��C0!7'!() A Guide for E11gi11eerl11g Students A Guide for E11gi11eeri11g Stmien ts
'-._ �_, __,,_ - -· ��
r
Microco11troller 4 - 28 · PIC 18FXXXX Microco11troller Arcl1itect11re Microcontroller 4 - 29 PJC 1 BFXXXX Microco11troller Arcltitect11re
Q.14 Explain different oscillator options with bit setting�. selectable clock frequencies, between 125 kHz to 4· :MI-Iz, for a
� [SPPU: May-19; Marks 8] total of 8' clock frequencies. This option gives the two oscillator
Ans. : Oscillator options : Essentially, there are three clock sources pins for use as additional general purpose I/O.
for the PIC microcontroller to operate in different modes of operation : • A Phase Lock Loop (PLL) frequency multiplier, available to both
Primary oscillators : The primary oscillators include the external the high-speed crystal and internal oscillator modes, which allows
crystal and resonator modes, the external clock modes and the internal clock speeds of up to 40 MHz used with the internal oscillator, the
oscillator block. The particular mode is defined by the FOSC3 :POSCO PLL gives users a complete selection of clock speeds, from 31 kHz
configuration bits. to 32 MHz - all without using an external crystal or clock circuit.
·Secondary oscillators : The secondary oscillators are those external Configuration Registers for Oscillator Options
sources not connected to the OSC1 or OSC2 pins. These sources may
• Many . features of the PIC can be selected using the bits in
continue to operate even after the controller is placed in a power ,·
Configuration Bit Settings Q.15 Explain in detail oscillator control register OSCCON.
Ans. : OSCCON : Oscillator Control register
• The configuration bits can be programmed (read as '0'), or left un
programmed (read a.S 'l ') , to select various device configurations. • The OSCCON register controls several aspects of the device
These bits are mapped starting at program memory location clock's operation, both in full-power operation and in power
30.0000H. managed modes. The system clock select bits, SCS 1 :SCSO, select
• The user will note that address 300000H is beyond the user the clock source. The oscillator control register is shown in
program memory space. In fact, it belongs to the configuration Fig. Q.15.1.
memory space (300000H - 3FFFFFH), which can only be accessed • The available clock sources are the primary clock (defined by the
using Table Reads and Table Writes. FOSC3:FOSCO configuration bits in CONFIG lH register), the
• Programming the configliration registers is done · in a ·manner secondary clock (Timerl oscillator) and the internal oscillator
similar to programming the FLASH memory.� The only difference block.
is the configuration registers are written a byte at a time. The • The internal oscillator frequency select bits, IRCF2 : IRCFO, select
configuration bit settings are shown in Table Q.14.2; '
the ·frequency outp_ut of the internal oscillator block to drive the
,,_......,,.
-'•W,_.,,.
device clock.
"'·""•'
r- '
0=Device enters Sleep mode on SLEEP instruction
;J:Jt£<2lfil�7h
______
boooooHl lEBTRBi Bit 6-4 : IRCF2:IRCFO: Internal oscillator frequency select bits
!··�·��
CONFIG7Hc> -""'!""' ---r-·--··r-·
! .,
l
---�----!�""-�
- - - -
; 1
·- .
1--·------+--+---+--+-LI
..-·--- _,,_,,,_ , __,,, ''.
13FFFFEHI DEVIDI DE\"2 i DEVI I DEVO ! REV4 REV3 REV2 REV! REVO
' ' ' j l
111=8MHi (INTOSC drives clock directly)
> I ' """''�. l
----
110 4 :Mllz
!3FFFFFHI DEVJD2 ! DEVIO I DEV9 l DEV8. D�V7 i DEV6. I DEVS DEV4 lDEV3 I �:::�. . I
=
101=2MHz
,....,,w,.{
. ·
>
..,,...,.,,....,,
. ....,. ......J.
.. ............�...,
.. .,..;.,.,....,�,!,,,.,
�-. . - ,...��-
,.,..,.,,,..,.. � L,..............w.-.-�·�- WNJfHUo'h....w..... \\wM.....
011 = 500 kHz • The Run and Idle modes may use any of the three available clock
010 = 50 kHz sources (primary, secondary or internal oscillator block); the Sleep
mode does not use a clock source.
·
· ·
000 = 31 kHz (from either INTOSC/256 or INTRC CPU is to be clocked or not and the selection of a clock source.
directly) • The IDLEN bit (OSCCON<7>) controls CPU clocking,_ while the
Bit 3 : OSTS : Oscillator Start-up Time-out Status bit SCS1 : SCSO bits (OSCCON<l :O>) select the clock source.
1 = Oscillator start-up timer time-out has expired; OSCCON : Oscillator Control Register
RlW -.1 RNJ 1 RJW 0 RJW 0 R R·O R/W·O RNJ-0
primary oscillator is running . · • • .
1 = INTOSC frequency is stable 1. Selection of Clock Sources : Primary Clock OSC2 : OSCO, The
secondary clock (the Timer 1 oscillator) and the internal oscillator
0 INTOSC frequency is not stable
block (for RC modes).
=
Q.16 Explain various power down (Managed) modes of PIC18FXXX. a. Switching from one power-managed mode to ai;.other begins by
loading the OSCCON register. The SCS1: SCSO bits select the
IEW" [SPPU: May-22, Marks 6, May-18,19, Marks BJ
Ans. : Power Managed (Down) Modes : clock source and determine which Run or Idle mode is to be
used. Changing these bits causes an immediate switch to the
PIC18F2455/2550/4455/4550 devices offers total of seven
new clock source, assuming that it is running.
•
·
o Idle modes c. Depending on the current mode and the mode· being switched
o Sleep mode. to, a change to a power-managed mode does not always require
setting all of these bits.
• These categories define which portions of the device are clocked
d. Executing a. SLEEP instruction does not necessarily place the
and sometimes, what speed.
device into Sleep mode. It acts as the trigger to place the
controller into either the Sleep mode, or one of the idle modes,
........
. .... . ....
. ;;;; ;; ..
. ..
... ..
... ..
... ..
... ..
... ..
... ..
... ..
... ..
... ..
... ..
... ..
... ..
... ..
... ..
... ..
... .......
... ..
... ..
... ..
... ... �.�
.. ...
� A Guide/or E11gi11eeri11gSt11dents'
� A G11idefor E11gi11eeri11g S111de11ts
1t e
Mlcroco 1 roll r 4 - 34 PIC IBFXXXX Mlcroco11troller Arcllitectu re Microco11troller 4 35 PIC IBFXXXX Microco11trofler Arcltitect11re ·
•
depending
.
on the setting of the ID
.
LEN bit..
. o SEC_RUN mode is entered by setting the SCSl:SCSO bits to
e. Available power managed modes is shown in Table Q.16.1. '01 ' . The device clock source is switched to the Timer 1
oscillator and the primary oscillator is shut down.
· C. RC_RUN MODE :
o In RC_RUN mode, the CPU and peripherals are clocked from
the internal oscillator block using the INTOSC multiplexer; the
primary clock is shut do"Wn.
o When using the INTRC source, this mode provides the best
power conservation of all the Run modes while still executing
Table Q.16.1 : Power managed modes
code.
Q.17 Explain RUN power down (Managed) mode of PIC18FXXX. o It works well for user applications which are not highly timing
Q" [Marks 6] . sensitive or do not require high-speed clocks at all times.
Ans. : Run modes : In the run modes, clocks to both the· core and o If the primary clock source is the internal oscillator block
peripherals are active. The difference be1'veen these modes· is the (either INTRC or INTOSC), there are no distinguishable
clock source. differences between the PRI.:..RUN and RC_RUN modes during
A. PRI_RUN MODE : This is also the default mode: upon a device execution. However, a clock switch delay will occur during
micr<:>controller. Depending on the primary clock source the IOFS primary clock source is the internal oscillator block, the use of
bit may be set in oscilla�or control register. RC_RUN mode is not recommended..
0 ·-
Ans. : Sleep Modes • If the IDLEN bit is set to "1" when a SLEEP instruction is
executed, the peripherals will be clocked from the clock source
• The power-managed Sleep mode in the
selected using the SCS 1: SCSO bits; however, the CPU will not be
PIC 18F2455/2550/4455/4550 devices is identical to the legacy
clocked. The clock source status bits are not affected.
Sleep mode offered in all other PIC devices.
• Setting IDLEN and executing a SLEEP inst�uction provides a
• It is entered by clearing the IDLEN bit (the default state on device
quick method of switching from a given Run mode to its
Reset) and executing the SLEEP instruction.
corresponding idle mode.
• This shuts down the selected oscillator. All clock source status bits
If the WDT is selected, the INTRC source· will continue to operate.
·
•
are cleared. ·
If the Timer 1 oscillator is enabled, it will also continue to run.
• Entering the Sleep mode from any other mode does not require a
• Since the CPU is not executing instructions, the only exits from
clock switch.
any of the idle modes are by interrupt, WDT time-out or a Reset.
This is because no clocks are needed once . the controller has entered
• ·When a wake event occurs, CPU execution ·is <;ielayed by an
Sleep. If the WDT is selected, the INTRC source will continue to
interval of TCSD while it becomes ready to execute code.
operate. If the Timer 1 ..oscillator is enabled, it will also continue to
run. • When the CPU begins executing code, ·it resumes with the same
clock source for the current idle mode.
• When a wake event occurs in Sleep mode (by interrupt, Reset or
WDT time-out), the device will not be clocked until the clock
• The IDLEN and SCS bits are not affected by the wake-up.
source selected by the SCS 1 : SCSO bits becomes ready or· it will • While in any Idle mode or Sleep mode, a WDT time-out will result
be clocked from the internal oscillator block if either the Two in a WDT wake-up to the Run mode currently specified by the
Speed Start-up or the Fail-Safe Clock Monitor are enabled. SCS 1: SCSO bits.
• In either case, the OSTS bit is set when the primary clock is A. PRI_IDLE MODE :
providing the device clocks. The IDLEN and SCS bits. are not
o It is unique among the three low-power Idle modes which does
affected by the wake-up.
not disi:tble the primary device clock during timing sensitive
applications, this allows for the fastest re<Jumption. of device
Q.19 Explain IDLE power down (Managed) mode of PIC18FXXX.
operation, with its more accurate primary clock source.
�[Marks 6]
o PRI_IDLE mode is entered from PRI_RUN mode by setting the
Ans. : Idle Modes
.IDLEN bit and executing a SLEEP instruction.
• The Idle modes allow the controller'!! CPU to be selectively shut
If the device is in another Run mode, set IDLEN first, then clear
down while the peripherals continue to operate. Selecting a
o
particular idle mode allows users to further manage power · the SCS bit3 and execute SLEEP.
cor.sumption.
'
r
. x
Microco11troller
o
4 - 38 PIC I8FXXXX Microco11troller Arcllitecture
o
4 39 PIC 18FXXXX Microco11troller Arcllitecture
•
j
FOSC3:FOSCO configuration bits. The OSTS bit remains set. Run mode, first set IDLEN, then set the SCSI bit and execute
. 0 When a wake event occurs, the CPU is clocked from the SLEEP. Although its_ value is ignored, it is recommended that
primary clock source. A delay of interval TCSD is required SCSO also be cleared; this is to maintain software compatibility '1.:11
·I
between the wake event and when ·code execution starts. It is with future devices. t
required to allow the CPU to become ready to execute o The INTOSC multiplexer may be used to select a higher clock
.1 r
fj
�
instructions.. frequency by modifying the IRCF bits be:!'ore executing the .I
. SLEEP instruction. When the clock source is switched to the 1
o After the wake-up, the OSTS bit remains set. The IDLEN and 1
SCS bits are not affected by the wake-up. INTOSC multiplexer, the primary oscillator is shut down and '
the OSTS bit is cleared. .l
B. SEC_IDLE MODE : J
o If the IRCF bits are set to any non-zero value, or the INTSRC
o In this mode, the CPU is disabled but the peripherals continue bit is set, the INTOSC output is enabled.
to be clocked f�om the Timer 1 oscillator: This mode is entered
o If the IRCF bits were previously at a non-zero value, or
from SEC_RUN by setting the IDLEN bit and executing a
INTSRC was set before the SLEEP instruction was executed
SLEEP instruction.
and the INTOSC source was already stable, the IOFS bit will
o If the revice is in another Run mode, set IDLEN first, then set remain set.
SCS 1: SCSO to '01' and execute SLEEP. When the clock source
o If the IRCF bits and INTSRC are all clear, the INTOSC output
is switched to the Timer 1 oscillator, the primary oscillator is
will· not be enabled, the IOFS bit will remain clear and there
shut down, the OSTS bit.is cleared and the TIRUN bit is set.
will be no indication of the current clock rnurce.
o When a wake event occurs, the peripherals continue to be
o When a wake event o�curs, the peripherals continue to be
clocked from the Timer 1 oscillator. After an interval of TCSD
clocked from the INTOSC multiplexer. After a delay of TCSD
following the wake event, the CPU begins executing code being
. following the wake event, the CPU begins executing code being
clocked by the Timer 1 oscillator.
clocked by the INTOSC multiplexer.
o The IDLEN and SCS bits are not affected· by the wake-up;
the
o The IDLEN and SCS bits are not affected by the wake-up. The
Timer l oscillator continues to run.
·
o In RC_IDLE mode, the CPU is disabled but the peripherals Q.20 Explain with diagram peripheral support in .PIC18FXXX.
continue to be clocked from the internal oscillator block using
Ans: Brief Summary of Peripheral Support
the INTOSC multiplexer. This mode allow� for controllable
·
(D @ @ @ Extended to
PORTB (address ofF81)
o Modules 0,2 (8-bits) standard CCP is that it allows four pins for implementation of H
o Modules 1,3 ( 16-bits) bridge or half H bridge for DC motor control. 1, 2 or 4 PWM
outputs
• CCP modules :
• 8-bit or 16 bit timer/counter 3. Synchronous - Slave (haJf duplex) with selectable clock
polarity
• 8-bit software programmable pre-scaler
• Internal or external dock f. Parallel slave port
• In addition to its function as a general VO port, PORTD can also
• Select interrupt on overflow from FFH to OOH
operate as an 8-bit wide Parallel Slave Port (PSP) or
• Edge select for external clock microprocessor port.
• Timer 1 is 16 bit .timer/counter and cannot be operated in 8 bit. • PSP operation is controlled by the four upper bits of the TRISE
• Timer 2 is an 8-bit timer with a pre-scaler. It can be used as the register.
PWM time-base for the P� mode o°fthe CCP module(s). • Setting control bit, PSPMODE (TRISE<4>), enables PSP
• Timer 3 is 16 bit timer/ counter and c.annot be operated in 8 bit. operation as long as the enhanced CCP module is not operating in
dual output or quad output PWM mode. In slave mode, the port is
It also works in CCP mode.
asynchronously readablt: and writable by the external world.
d. Mas�er Synchronous Serial Port (MSSP) module • The PSP can directly interface to an 8-bit microprocessor data bus.
• The Master Synchronous Serial Port (MSSP) module is a serial The external microprocessor can read qr write the PORTD latch �s
an 8-bit latch.
interface useful for communicating with other peripheral or
/
microcontroller devices. These peripheral devices may be serial Important Points to Remember
EEFROMs, shift registers, display drivers, A/D converters, etc. 1. PIC uses Harvard architecture with RISC instruction set
The MSSP module can operate in one of two modes: architecture
1. Serial Peripheral Interface (SPI) 2. Clock is DC- 40 MHz
2. Inter-Integrated Circuit (I2C). 3. Has in build Timer/Counter, Serial port ADC,
e. Enhanced universal synchronous asynchronous receiver 4. Instructions are of 2, 4 bytes long
transmitter
5. Families are not upward compatible.
• The EUSART can be configured in the following modes:
6. _Incorrect programmilig of Configuration register can cause
1. Asynchronous (full duplex) with: system to fail
o Auto-wake-up on charac�er reception' 7. . 2f-bit address bus for program memory addressing capacity .
o Auto-baud calibration " 2 MB of memory
o 12-bit break character transmission.
8. 12-bit address bus .for data memory addressing capacity: 4 KB·
· 2. Synchronous - Master (half duplex) with selectable dock of memory
polarity �
'\
A G11ide for E11gi11eel'i11g Students
_.:··:2..::�!.: '" --"' C11h/e for Engi�1eeri11g S111de11ts �
����_1vj
Microco11tro//er 4 - 44 P/C 1BFXXXX Microco11troller Architecture �--��
9. Has 77 Instructions
10. 16"bit instruction/data bus for program memory
11. 8-bit data bus for data memory Peripheral Support in
12. Has four tim�r,- timer 0 (8 and 16 bit) timer 1 and 3(16 bit), PIC 18FXXXX
timer 2 and 4 (8 bits only) .[§Jb��
13. MCLR plays important role in reset operation of PIC
Q.1 Draw and explain functional diagram of timer 0 of Pl C and __
II }3
TOPS2.TOPS1.TOPSO
.
P�A l
Set lnterrnpt
Flag bit TMHOIF
TOGS on Overflow
END . 25
. .
•
----,,
i
o
counter mode, Timer 0 increments either on every rising or
o After loading TMROH and TMROL, the timer must be started.
falling edge of pin RA4/TOCKI/C10UT/RCV.
o Count up till it reaches FFFFH, then it rolls over to 0000 and
o The incrementing edge is determined by the Timer 0 Source activate TMROIF bit.
Edge Select bit, TOSE (TOCON<4>); clearing this bit selects the o Then TMROH and TMROL must be reloaded with the original
rising edge. value and deactivate TMROIF bit.
TM ROH TMROL
o Restrictions on the external clock input : An external clock
source can be used to drive Timer O; however, it must meet r -- '.,/' -,
certain requirements to ensure that the external clock can be 1"1�1§;j;11•111�,1111�11,�1�111�1,l'.zl�r11;:;9m1:!:i�%l!�!l1j11:11!fl§wli12111��*11111 ;w¥il!1'w�1::1;;;gµ;.:1
synchronized with the internal phase clock (TOSC). There is a
delay between synchronization and the onset of incrementing MOVWF TMROL : Loads 'W' register into TMROL
the timer/counter.
MOVFF TMROL, PORTB : Loads TMROL value into PORT B.
o An 8-bit counter is available as a pre-�caler for the Timer 0
o TMROH is not the actual high byte of Timer 0 in 16-bit mode. It
module. The pre-scaler is not directly readable or writable; its
is actually a buffered version of the real high byte of TimerO
value is set by the PSA and TOPS2:TOPSO bits (TOCON<3:0>)
which is not directly readable nor writable.
which determine the pre-scaler assignment and pre-scale ratio.
'oc��4r;;;;:I
o CJearing the PSA bit assigns the pre-scaler to the TimerO Se;
..,... Ti't�R.oF:
module. Whert it is assigned, pre'.'scale values from 1 :2 through cm overflc.1w
o When assigned to the Timer 0 module, all i,nstructions writing TOPG2·TOPSO------' -ReadTMROL
0PSA
-·
T n WritE:! TMRCL
to the TMRO register (e.g., CLRF TMRO, MOVWF TMRO,
BSF TMRO, etc.) clear the pre-scaler count.
TMROIE bit (INTCON<5>r Before re-enabling the interrupt, 0 during a read of TMROL. This provides the ability to read all
16 bits of Timer 0 without having to verify that the read of the
high and low byte were valid, due to a rollover between Ans.: Timerl : 16 bit operation
successive reads of the high and low byte.
The Timer 1 module incorporates following features
o Similarly, a write to the high byte of Timer 0 must also take
1. Software•programmed i'n 16-bit mode only and does not support
place through the TMROH Buffer register. The high byte is
8-bit mode.
updated with the contents of TMROH when a write occurs to
TMROL. This allows all 16 bits of Timer 0 to be updated at 2. It has 2 bytes named as TMRlL and RMRlH which are readable
and writable [It can count up 65.535 pulses in a single cycle].
once. .
.
Note: Load TIMEROH first and th�n TIMEROL since TIMEROH will 3. Selectable clock source (internal or external) with device Clock or
.· be kept in temporary reg. to avoid the errors during counting if Timer 1 oscillator internal options.
TIMEROON flag is set to high. 4. Has four prescale values [1:1, 1:2,1:4,1:8].
Microco11troller 5-6 Periplleral S11pport i11 PIC 18FXXXX Mir:roco11troller 5-7 Periplleral S11pport i11PIC18FXXXX
CCP Special Event Trigger
Ans. : TOCON Reg - Timer control Register-8 bit
87 86 85 94 93 82 81 BO
TMR10N
on/off T1SYNC
1 = Enables TimerO I !
J
110" 1:128 '010" 1:8
l=8 - bit Tinier/Counter .
101 1 :64
= 001 1· :4 =
. provide an additional clocking· option. The timer 1 oscillator 01=1:2 I (Ri$lng edge;
00 = 1:1 ! 0 = lntemai clock
can also be used as a low-power clock source for 'the 1 "
'
No synchronizat:on of externa! c!ock !nput
microcontroller in power-managed operation. 0 = Syric:hronlzaiion of exte�i1(il clock inp1.1t
·J ·
I Q,4 Explain operation of timer 2 of PIC 18FXXX.
functionality to applications with only ,a minim
. al addition of
(
. � [Nov.-15, Marks 8)
external components and code overhead.
o Timer1 is .
controlled through the T 1 CON ''Control register , Ans. : Timer 2 : 8 bit operation
shown i� Fig.
.
Q.19. 1. I�
also contains the timer 1 oscillator .
. .
setting or clearing control bit, TMRI ON (Tl CON<O>).
.
enable b1t (TlOSCEN). timer 1 can be enabled or disabled by
.
·
•
•
It is an 8 bit register with 8-b'it period register (PR2)� Fixed value
, ;; I
·,:II
• TMR2IF flag from PIRl reg. is raised and TMR2 reset to 00.
;I
Q,3 Explain operation of TOCON and TlCON registers of PIC
. • The clock sourc·e f<;>r TMR2 is Fosc/4 for both prescaler and
18FXXX. ' ll':i" [Nov.·15, Marks 8)
postscaler options. ;':11
• There is no extem�l clock source, hence cannot be us� as counter. :!;li
'·:
1
!!
• Three prescale values (Bit 1 - Bit 0) and 16 postscale . values
(Bit 6 - Bit 3) in T2CO'N register are used to calculate the delay.
•·
::11
�� A G!!ide for E11gi11eeri11g Sllldell!s � A Guide for E11gi11eeri11g Studellls
/il
Microco11troller 5-8 Periplteral Support 111 PIC 18FXXXX
Microcontro/ler 5.9 Peripl1er<1l Support in PIC 18FXXXX
,._
• Flag (T:MR2IF) is set when T:MR2 matches PR2 : Can generate an 84 83 82 B1 BO
interrupt.
.. Tiv1R2 register;
I .
0001=1:2
00 = 1 :1
0000 = 1:1
3. Both prescaler and postscaler are cleared by writing to the
Fig. Q.4.2 : Timer 2 control register
T2CON register;
.
mode.
• Timer ·2 can be optionally used as the shift clock source for the
MSSP module operating in SPI mode.
Fig. Q.4.1 : Timer 2 block diagram
Q.5 Write a C18 program to toggle all bits of port B continuously
The module is controlled through the T2CON register Fig. Q.4.2,
·
•
3. N= 10 ms/0.4 µs = 25000
4. Count= 65536-25000 = (40536)10 2. The calculations used for program 1 are same hence
5. H!!X value to be loaded= (9E 58)16 · T11R.OH = 9EH and T11ROL = 58 H
6. Load T11R.OH = 9EH andT11R.OL = 58H
#includ e <Pl8FXXXX.h>
void TODelay(void); {
void main(void) TRISB=O; . 11 configure port B as output
While(l)
{
TRISB=O; 11 configure Port B as output . {
While(l) J:>ORTBbits.RB 1 = O; II set RB I bit high
TODelay ( );
{
PORTB= Ox55; II Load bit patterns PORTBbits.RBI= l;
TODelay ( ); TODelay ( );
PORTE= OxAA; }
TCiDelay ( ); }
}
void TODelay ()
} ,,·,
{
void TODelay ( ) TOCON = O x 08; . II TimerO, 16 bit, no prescaler
TMROH = 0 x 9E; II Load Higher byte in TMROH
{
TOCON=Ox08; 11 TimerO, 16 bit, .no prescaler . i TMROL= Ox58; II Load Lower byte to TMROL
TMROH=Ox9E; 11 Load Higher byte in TMROH I TOCONbits.TMROON=l ; 11 Start the timer for upcount
TMROL= Ox58; II Load Lower byte to TMROL while(INTCONbits.TMROIF==O); II Check for overflow
2. Internal time delay= 4/(10*106)= 0.4 µs 2. Internal time delay= 4*4/(10*106)= 1.6 µs
#include <PlBFXXXX.h>
Q.8 Write a C18 program to generate frequency of 2500 Hz on all
void TODelay(void);
PORTC.2 c->nflnuously using timer 1 , 16 bit and no prescalar.
void main(void)
}
. Q.10 Draw and explain the interrupt structure of PIC18FXXX, what
void TlDelay () are peripheral Interrupts, IVT arid ISR.
Interrupts According to the block schematic, the interrupt may occur due to reset
I by CPU or any other program execution used by different peripherals.
i ·- -. internal interrupt; it sets the flag or theses interrupts are enabled by use
Non-Maskable Maskable
' of control registers. These interrupts are maskable interrupts. The
I vectored, internal or external interrupts causes the reset and a!! are
• ,l enabled by use of Global interrupt enable bit in INCONO control
External Internal registers.
sources sources
Fig. Q.10.1 Interrupt types Q.11 Di'.lW and explain INTCON register used ln Interrupt of the
• PORTB interrupt on change (RB4 - RB7) PIC18F4550.
• Comparator output change The INTCON registers . are readable and writable registers, which
contain various enable, priority and flag bits�
• AID conversion complete
I 1 RM-0I 1
RM-0 I
RM·O f._T
,.-···:-··-··-�--··T·-·------··-� - - ·--····-�----·------·-· ·-·-----·-·c····--.,._,,...
W--0 R/W-0 1 R/W--0
..,...,..._.._,._ .
R/W--0 1RM-x ;
... .,,, ....... .,.\
Communication channel events
I�IO,!.�=r�!-�l!��?>i�:J�!EI�fr1��if: J
•
Bit
____,,),
. !
__ --�--�--�--�••·•o••-•<·.�.·.om�wuN'•-·m,wmno,,
i I I [,
- I
31obal Interrupt Enable'
(Reset by
or program)
_g:� R
· l.__ ----'-I
Interrupt
flag·
I
:
:
) interrupt
-- inputs to
·
CPU
1 = Enables all high priority interrupts'
------------------------------:,._-- I
' 0 = Disables all high priority interrupts
Non-mas�k:_:a::b::_:el: :_ _______ _ __;
interrupt Bit 6 PEIE/GIEL : Peripheral Interrupt Enable bit
·--
---
•
• bits in a Special Function Register
When IPEN = 0 :
Fig. Q.10.2 General interrupt structure
1 = Enabies all unmasked peripheral interrupts
¥
1
!\
�:
i�I�!
'.11·
.•
.i
Microco11tro/ler
\:�
5 -19 Perip//eral Support i11PIC18FXXXX
Microcontroller 5 18 Perip/1eral Support 111 PIC 1 BFXXXX !!�
•
iiii
of
Q.12 Draw and explain PIRl register used In Interrupt the )1.
0 = Disables all peripheral interrupts
PIC18F4550. i1i
When !PEN= 1 : ctl!
Ans. : PIR Registers :·�j
'i\'
1 =Enables all low priority peripheral interrupts
·
· !<
The PIR registers contain the individual flag bits for the peripheral .:\\
:\\'•;Iii
0 = Disables all low priority peripheral interrupts interrupts. Due to the number of peripheral interrupt sources, there are
two Peripheral Interrupt Flag Registers (PIRl, PIR2). ·;�
• Bit 5 TMROIE : TMRO Overflow Interrupt Enable bit
1 =Enables. the TMRO overflow interrupt
:.\«,
·:!·
'':�'
..
Compare mode :
3. The ICPRT Configuration bit can only be programmed through
1 A TMRl register compare match occurred
the default ICSP port (MCLR/RB6/RB7).
(must be cleared in software)
'
0 No TMRl register compare match occurred 4. The power-managed Sleep mode in the
PIC18F2455/2550/4455/4550 devices is identical to the legacy
PWM mode: Sleep mode offered in all other PIC devices.
Unused in this mode
Fig. Q.13.1 shows interrupt strucfure in legacy mode.
• Bit 1 TMR2IF : TMR2 to PR2 Match interrupt flag bit
TMROI
'i Interrupts
�-----Wakeup
.··
Q.13 Draw and explain the legacy . and priority mode of PIC
interrupts. Ba" [SPPU: May-18, Marks 8)
Ans. : The PIC miCrocontroller has the two types of interrupts as Fig. Q.13.1 Interrupt structure (legacy mode)
High priority and low priority depending on the internal and external The CPU is interrupted by either by use of software interrupt as timer
sources. 0 enabled by TOCON register of any other core i�terrupts. The other
sources used TIMERl in: CCP modes will be· enabled by TMRlIE bit
of TlCON register. Also the other internal peripherals such as ADC,
JL'1
Microco11troller 5 22
• Perlp/1eral Support 111 PIC JBFXXXX
Microcontroller 5-23 . Peripheral Support i11 PIC IBFXXXX
USART and so on. These interrupt requires the authentication and will • Each interrupt source, except INTO, has three bits to control its
be enabled by uses of PEIE bit in INTONO. The 'CPU is interrupted
operation. The functions of these bits are :
only when GIE bit. of INCONO is set either for low priority.
1. Flag bit to indicate that an interrupt event occurred.
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-x 2. Enable bit that allows program execution to branch to the
interrupt vector address when the flag bit is set.
L��:���1::..����:J��?.�-�T��.L�� . l����IF_l��] .. ..
bitO
3. Priority bit to select high priority or low priority.
bit 7
Interrupt handling steps :
Interrupt structure (Priority mode) (External operath.:·n)
• The interrupt priority featur� is enabled by setting the IPEN bit
The PIC l 8FXX2 devices have multiple interrupt sources and an (RCON<7>). When interrupt priority is enabled, there are two bits
interrupt priority feature that allows each interrupt source to be which enable interrupts globally.
assigned a high priority level or a low priority level. The high priority • Setting the GIEH bit (INTCON<7>) enables all interrupts that have
interrupt vector is at 0008h and the low priority interrupt vector is at ,,
I the priority bit. set. Setting the GIEL bit (INTCON<6>) enables all
00 l 8h. High priority interrupt events will over-ride any low priority interrupts that have the priority bit cleared..
interrupts that may be in progress. The, general block diagram of
· • When the interrupt flag eriable bit and appropriate global interrupt
Priority mode is shown in Fig. Q.13.2.
·
enable bit are set, the interrupt will vector immediately to address
INTOIF-. INTOIE
000008h or 0000 l 8h, depending on the priority level.
r-
O =· Prescaler Assigned
1 " No Prescaler
1 = Failing edge
• Interrupt priority for INTI and INT2 is determined by the value O = Rising edge
\ ::, I g
contained 1n the interrupt priority bits, ·INTlIP (INTCON3<6>)
�
· :
�
Pro ram:
and INT2IP (INTCON3<7>). There is no priority bit associated
·
i,\I
'
1
-: 1 \[:;'.\
['ii
·111
with INTO. It is always a high priority interrupt source. void main(void)
{
:l' ! 'i
'. Q.15 Write an embedded C program to generate the delay of 100 TRISB= OxOO; II Port B as output
, 1: '.:;·
Timer Interrupt Program for Fosc 48 MHz..
I!
:
I'. , i�_ '.i
'
.
ms using
Ans.:
= LATB= OxFF;
RCONbits.IPEN = 1; 11 Priority Enable
I." INTCONbits.GIEH = 1; // High priority Interrupt
Step1 : CALCULATIONS of Delay (use Tmer 0 ,16 bit mode)
INTCONbits.GIEL= 1; 11 Enable Low priority interrupts
*required delay= lOOms
INTCONbits.TMROIE= 1; 11 Enable Timer 0 interrupts
* TMR value= OxFFFF - [(required time)/(4*Tosc*Prescaler)]
INTCONbits.TMROIF= O; 11 Disable Timer flag
= OxFFFF [(0.1*48000000)1(4*256)]
INTC0Ij2bits.TMRO-IP = O; 11 Disable TierO Priority
•
= OxFFFF - Ox124F
TOCON= Ox07; II Stop the timer, Run in 16-bit .node,
*TMRO = OxEDBO
//Use system clock, Use a 1:256 prescaler
*TMRH= OxED TMROH= OxED; 11 Load Timer
*TMRL= OxBO TMROL = OxBO;
or TOCONbits.TMROON 1;
= 11 Start the timer
SFRS used - No need in the exam.
1:.
Note : while(1);
TMROL
LATB
=
=-
OxBO;
LATB; '
'.l�' :
:i
TOCONbits.TMROON 1; II Start the timer
"
·:
=
. ·i1f
}
} CCPxCON register
Q.16 Explain the concept of CCP module with CCPX Control
register in detail. 7 6 5 4 . -1. 0
·�.....,..,.
...-. ..'f"mmn.•.w,.....,..,_ ,t'""'.....,..,WNMN·. ... .��
...,..,-, , ,...... . ?- w.
., ...,_w....,.... .....w
!" � ?
Ans. : Captu.re, Compare and PWM (CCP) Modules : ! - i l ocxBt I oc:illo l cci>xM3 : ccPxM2 i CCPxMI f cCPxMO
·
-
�u,.,..,L.,.......,.J....,.....,...,,.....,,.,,,....N.,w,, w,•ffMM'.WNh\�'= IYNN<o'NNM""...,.,. VJ,. ..,...,_..,,,.
. i. J ..,.,,....,,.•.....
..,.,,., ....,. , .,... ,•,v.-,v. ,.,._.,....,_.,..,__., ,...,.....,. ...,.,, ....,..._. .,....w,,w
• 16-bit Capture register 0010 Compare rnode, toggle output on match (CCPxIF bit is set)
• 16-bit Compare register 0100 Capture .mode, every falling edge
• Duty-cycle PWM register 0101 Capture mode, every rising edge
• Timer 1 used as clock for Capture and Compare 0110 Capture mode, every 4th rising edge
��®
�----- A Guidefor E11gineer/11g Stmle11ts
�® .d r:11irlo f11r r:'11oi11ao1•i11a C:t1u/ouf!;;:
Microco11troller 5- 28 Periplter"l Support 111PIC18FXXXX Microco11troller 5 - 29 Peripl1m1/ Support i11PIC18FXXXX
0111 = Capture mode, every 161h rising edge 3. Every-4th rising edge
1000 Compare mode, initialize CCP pin low, on compare match 4. Every 16th rising edge
force CCP pin high (CCPxIF bit is set) The.block diagram of CCP in capture mode is shown in Fig. Q.17.1
Setflag bit
1001 Compare mode, initialize CCP pin high, on compare match CCPx!F
Q.17 Explain in detail with block sch�matic capture mode of CCP • When a capture is made, the interrupt flag bit, CCPxIF is set.
module. � (SPPU: Dec-17, Marks 8, Nov-16, Marks 6] "
[PIRl register]
Ans. : CCP in the capture mode
• The CCPxIF flag must be cleared by software.
• CCPRl captures the 16-bit value of Timer 1 : When an event • In capture mode, the CCPx pin must be configured for input.
occurs on pin RC2/CCP1.
• The t.! mer to be used with the capture mode must be running in
• Interrupt request flag bit CCPlIF is set : Must be cleared for the timer mode or synchrono1:1s counter mode.
next operation
• To prevent 'false interrupt, the user must disable the CCP module
• To capture an event when switching pre-scaler.
o Set up pin RC2/CCP1 of PORTC as the input • The contents of TMR3H : TMR3L OR TMRlH : TMRlL are
I:' o Initialize Timer 1 : TlCON register loaded into CCPRX register.
i
...,,,_.,,,.,,,,
i
�. __ , ..
....
i
y., ...., .,._.,,..,,,.,...,. .....,..,..,,...__
.....,...... ....,,,.
B7 B6
·
• !
li !:
�")1�1
5 31 Peripheral Support In PIC 18FXXXX.
Microco'!troller -
Masier
"CPxCOl\!<5:4"
"-' ·
111111
} f11Q·nI "1· me
._,.
(dc<yoy<<o) � Step 1 : Calculation of PR2 = [ Tpwm I * 4 * TOSC * N] -1
N =Presale factor 2,4,16 (if not mentioned by default 16 and
D"Ooycl•
,--A--, TOSC=O.l µs]. Choose Pre scaler [TMR2PRE] to ensure that
Slave
I
:LSB ! =r
TMR2 = CCPRxH:2 PR2 is in the range of 0 to 255 for . the desired PWM
frequency.
I �:: I I I I
Step 2: Calculating the CCPRLl value (Lower 8 bits)=_% D * PR2
} Period,..--
------
-- --
25 '.'�DC
50 % DC
__fl_J - Ul_J Q.20 Write an embedded C program for 2.5 kHz and 75 % duty
=
75%[JC � cycle PWM generation with N 4
Q' [SPPU: Dec-18, Marks 8, Dec-1'7, Marks 8]
'
Ans. : PWM Generation
Fig Q.19.2 Duty cycle variations (Need to draw) Step 1: Find value of PR2
�R2= [fosc/fpwm*4�N] -1=[10 MHz/2.5 kHz*4*4] -1 =249;
• The PWM mode uses timer 2 whose value is compared with the
period register PR2 when match is found sets the FF and PWM - Step 2: Find yalue of CCPRlL
wave is obtained on RC2 pin. At the same time it is set by match CCPRxV= PR2*DC=249*0.75= 186.75-186;
with contents of CCPRl register.· The PWM mode uses different
SFRs as CCPxCON, T2CON, PIRl and TMR2 is cleared
CCPRxL. The configuration of PWM mode follows the following
steps.
i
�ill
·m
\I;
}
}
1111=1:16
1110=1:15 Q.21 Write an embedded C program for 1 kHz and 10 3 duty cycle
I PWM generation. Qr [SPPU : May-22, Marks 8,M?_v-15,16, Marks 8)
0001 = 1 :2
0000=1:1 Ans. : PWM Generation
Step 3 : Set 'theTMR2 pre-scaler value, then enable TMR2 by writing Assume that Fosc = 10 MHz, Ifpresclar is not giwn then N = 16
•
toT2CON Step 1 : Find value ofPR2
T2CON=Ox01;(pre-scaler=4 00-1:1, 01-1:4; and lX-1:16) 00000001 PR2 = [fosc/fpwm*4*N]-1= [10 MHz/1kHz* 4 * 16] -1 =156;
Step 2: Find value ofCCPRlL
Step 4 Configure the CCPx module for PWM mode set DC1B2 and
·
:
CCPRxL = PR2*DC= 155*0.1= 15.6-16;
DClBl (or decimal portion of the duty cycle.
Step 3 Set the TMR2 pre-scaler value, then enable TMR2 by
:
CCP1CON=Ox3C;(CCPxCON<5:4> =11for75% DC&l lXX--PWM)
writing toT2CON
87 86 85 84 63 82
T2CON = Ox02; �pre-scaler=16 00- 1:1,01-1:4;
and 1X-1:16)0000001x
Step 4 Configure the. CCPx module for PWM mode set DC1 B2 and
:
DC1B1 for decimal po1tion ofthe duty cycle.
CCPlCON = OxOC; (CCPxCON<5:4> = 00for 10% DC
and 1 lXX-PWM)
Program:
Program:
#include <Pl8F458.h>
#include <P18F458.h>
Void main (void)
Void main (void)
{
CCPlCON=O; //clear the Reg {
CCPlCON=O; // clear the Reg
PR2=249; 11 load the PR2 value
PR2=155; // load the PR2 value
CCPR1L�l86; II 10%DC
CCPR1L=16; // 10 %DC
TRISCbits.TRISC2=0; /I make PWM pin output ·
I
{ // Check for the timer fiag
'{ 11 Check for the timer fl;,,_g
� A G11ide for E11gil1eeri11g St11dents
,-� A G11idefor £11gi11eeri11g Students
�
Microco11trol/er 5. 36 Periplleral S11pport i11PIC18FXXXX Micrqco11troller 5.37 P,�ripllerlll Support 111PIC18FXXXX
PIR1bits.TMR2IF=O; // clear timer2 flag. • NPN transistor speed control : When motor js off, parallel diode
While (PIR1bits.TMR2IF= =O); //wait for end of period acts as freewheeling for dissipation of energy.
} +5V
}
1111111
· 1111
5 Volts
t
- +
0 Volts
Duty cyc!e {% 50 % ·- { Low value
resislor
Fig. Q.22.1 Pulses with O % th�ough 50 % duty cycle
• The average DC voltage value for 0 % duty cycle is zero; with '
25 % duty cycle the average value is 1.25 V (25 % of 5 V). With Zener diode
ADC·voltage
50 % duty cycle the average value is 2.5 V _and if the duty cycle is reference
75 %, the average voltage is 3.75 V and so on. The maximum duty
cycle can be 100 %, which is equivalent to a DC waveform. Thus
by varying the pulse-width, we can vary the average voltage across
a DC motor and hence its speed. The speed of DC motor can be
controlled using variety of methods as shown in Fig. Q.22.2 to
-=:
Fig. Q.22.4, out of which H-bridge is mostly preferred. Fig. Q.22.3 : Tr�nsistor control
� r
A Gufr/e fo E11ginee1"i11g Students
�
A Guide for E11gi11eer/11g Students
i!
"
;iill
J '
·1, . l 2
·
MOSFETs etc. rather of being cheap, they only increase the size of .
the design board, which is sometimes not required so using a small
16 pin IC is preferred for this purpose.
r
switching circuit which controls the motion of the motor.. It is also
_, known as "full bridge". Basically there are four switching elements
in the H-bridge as shown.in the Fig. Q.23. L
· Motor pqwer (+)
· Motor power(+)
·I
i
·�
motor using the full H-bridge circuit as shown in Fig.
Q.22.4.
Y
interfaced with PIC using H bridge <••l
As can seen in the Fig: Q.23. 1. there are four switching elements
2. Set the PWM duty cycle by writing to the CCPRlL register a?-d
•
named as "high side left", "high side right", "low side right", "low
CCP1CON<5:4> bits.
side left". When these switches are turned on in pairs, motor
·
and high side right, the current flows in opposite direction and. OxF9;
motor rotates in backward direction. This is the basic working of
.''i<\ "'�-.� ::�
t�!
. �
.
H-bridge.
""4
,. .�:�L. . . .: ., .. .. .
.. ... .. .
. . . .. ... .. .. !
-:..�l I
Uses the PWM mode to control the speed
• Uses the timer 2 with increased frequency either internal or ' �J..r.�:..:·�
�;:. -:
rn·�
external. The transistorized speed control is shown in Fig. Q.23.2. wo
Vod !
. .
VrJd VcM
\i .r Ii
l.<;iiSf>
'�®
•
tl
SPDT
f?\l,
.. .
i 0�1 T. .. .. . ......-1�.
� iN9!4 �r
..-.. ·- -·
..�....... . .. �
-
,:J'J"
j !;.I- \ �
'J 10
<\<;'.:'...,
. . . ..
.. .
,,\, v·
\ \ l r I1
,'ci:�o; ..�:.(0
2No90.S ! ···..······
1
I
·····
! �N'.>
l. 14
<l i
-;:,
�
_Li/\ '
Vl/v\--i1l
1()0 ·11J\)
v'vV1r -'-----+-:<i ........,
i'
r---:
6.0V
··
':
."
I ·=�====:
ZN3S04 ;;.NJS(l4
I
1
?IC16F4!50
== :::;
.
1 L·--····-- -· ==:_
::::. _Jj Fig. Q.24.1 DC motor PWM speed control using IC 293
, embedded C program for increasing and decreasing speed with writing to T2CON
interrupt using key. � [SPPU: May-15, Marks 8] T2CON = OxO1; (pre-scaler= oo. 1 :1, 01-1:4;
.
PWM frequency = 2.5 kHz CCPlCO�'IJ"=OxOC; (CCPxCON<5:4> =00 for 10% DC and.
� ' llXX--PWM)
.�)
PR2= [fosc/fpwm*4*N] -1= (10 MHz/2.5 kHz * 4 * 4)- 1
unsigned char count=O;
= 249 or
bit TIMER,SPEED-UP;
.,
·
·��
'\
}
els� SPEED_UP = O;
• TheADC module can 12 channels associated with port A,E,B
• The AID converter has a unique feature of being able to operate • Each port pin assoCiated with the A/D converter �an be configured
while the. device is in SLEEP mode. To operate in SLEEP, the AID as an analog input (RA3 can also be a voltage reference) or as a
conversion clock must be derived from the A/D's internal RC digital IIO.
oscillator. • The ADRESH and ADRESL registers contain the result of the AID
• The output of the sample and hold is the input into the converter, conversion. When the AID conversion is complete, the result is
which generates the result via. successive approximation. loaded into the ADRESH I ADRESL registers, the GO/DONE bit
• The functional diagram of ADC in PIC is as shown in Fig. Q.25. l (ADCON0<2>) is cleared, and AID interrupt flag bit, ADIF is set.
CHS3:CHSO • Channels are selected by use of '<'.:HS2:CHSO of DADCONO
UJL . , register
r--""" 1100 i
� _ _ _ _ .
:
[8J AN12 • After the AID module has been configured as desired, the selected
t=='� 1010:
1011 :
""f2J AN11 channel must be acquired before the conversion is started. The
[8J AN10
"""
� ''o-:!001 :I analog input channels must have their corresponding TRIS bits
IZJ AN9 selected as an input.
�""" 1000 : . IZJ AN8
i--., � 0.111 : . IZJ AN/11 • An acquisition time can be programmed to occur between setting
I ., 0110 I I!) the GO/DONE bit and the actual start of the conversion.
.., ......o ...,___;.-
I ....... � AN6
JV'! ____
(1l
t--<. � AN5
Q.26 Explain various registers used by ADC in PIC 18.FXXXX.
1 � o·oo'
I VAIN : t---" ' : � AN4
0011
·.
....._.,
(Input voltage) - �. Ans.: Various registers of ADC:
...... I
.IV'!
-·� '� N.?
'
T
: h '·, 001b I AN2
�
I
: L -'
:r
0001 I
AN1
1. ADCONO : AID control register 0
VCFG 1 :VCFGO
--JL
VD0'2J : 1...-o 0000 1
I
ANO
The ADCONO register controls the operation of ·the· AID module.
�...::xoJ ADCONO register is used to set the conversion time and select the
I
VREF -: ;,.-
"".°�' �i�===--------
0
'7ox
.. channels. For power saving ADC feature is turned off when power up.
1 •v 0
- - - - - _, And turned on with ADON bit when required. GO/DOWN bit is used
1 for start and monitor the end of conversion.
"'::- r2·1
vss· ·
Fig. Q.25.1 ADC functional diagram U-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 RIW·O R/W-0
'
- I- lvcFGI I VCFGO I PCFG3 I PCFG2 I PCFGI I PCFGO loaded, with 'O's. When an AID result will not overwrite these
bit7 bitO locations (ND disable), these registers may be used as tWo general
purpose 8-bit registers.
ADC control register 1
• Result registers are shown. in Fig. Q.27� 1
3. ADCON2 : AID control register 2
]
t
ADFM = 0
in the ADRESL and ADRESH is right or left justified by ADFM bit ,..----A--., ,..----A--.,
7 2107 0 7 0765 0
R/W-0 U-0 R/W-0 R/W-0 Riw-o R/W-0 R/W-0 R/W-0 I0000 oo :1,�111rn1wim111.:miil . l!!Wiiirnr;:J!MJrH!Ii 0000 00 I tli
'--y---1 '----..,,.-� � '--y---' :�
ADFM I ... I ACQT2 I ACQTI I ACQTO I ADCS2 I ADCSI I ADCSO ADRESH ADRESL ADRESH ADRESL ·�1
'l.j
� � {
bit 7 bit 0
' ��
� , ___
A Guide for £11gi11eeri11g Stude11ts
� A Guide for E11gi11eeri11g Sii/dents
::
.:\�
I
I
Microco11troller 5- 48 Perip/1em/ Support i11 PIC 18FXXXX Microco11troller 5-49 Perip/lera/ Support ill PJC 18FXXXX
sv
Note : Solution problem statements modified --- Interfacing diagram
will change.
•.j. "..:.\.�:���-
Fig. Q.28.1 (b) Sensor Interface to PIC
, Program
0,
.
H;;I.'
#include <p18f4550.h>
·
#include <stdio.h>
#include "LCD_SIT.h"
const unsigned char LCD_Datal[ ]={"ADC Value="};
L-u---1 void DisplayResult(unsigned short hexVal);
: ·fi;; ?<,�:--i� :
,. . . .. . . ! {
· unsigned char z=O,hexVal;
+ +
:""··········
TRISEbits.RAO,., l; // ADC channel 6 input
I'·'
Om TRISEbits.RAl = 1:
Init_LCD();
// ADC channel. 7 input
11 DDDDAAAAAA
Pi('.�6�$77.4
APCON2=0xAE; //AID Result Format Select bit -
·//Right justified,
Fig. Q.28.1 (a) Interface with LCD display ·
ji"
;i
·:i.
1
H1
� A Guitlefor E11gineeri11g Students � A Guidefor E11gi11eeri11g S111de11ts
'
. '.
�I'
} }
while (1)
tempv<<=l;
{ }
ADCONObits.ADON = 1; //AID On bit- on
}--�������- -��
ADCONObits.CHS = OxOO; //Analog Channel Select bits?
ADCONObits.GODONE = 1;
II ch n0-7(ADC1)
//AID Conversion Status bit ...
Important Points to Remember
1. PIC18F has 4 timers, timer 0 : 8 or 16 bit, timer 1 and 3 : 16
"J1,.I
//conversion in progress
while(ADCONObits.GO_DONE == 1 );
ADCONObits.ADON = O; //AID On bit· off 2.
bits, timer 2 : 8 bit
�
Each ti er has its control register TCONx
�
·...
I1
DisplayResult(ADRES);
3. Timer is used to find the time delay.
} 4. To increase the required delay pre and post scaling is used.
}
5. Timer 0, 16 bit, TMROH is loaded first then TMROL
void DisplayRasult(unsigned short hexVal)
6. Highest delay will be generated when TMROH=TMROL= OOh
{
unsignad chnr i,text[l6]; 7. PIC18F4550 has 3 External Interrupts (INT0-2)
unsigned short tempv;
tempv = hexVal; 8. Interrupts are categorized as Jow priority and high priority
hexVal = (5200/1024)*tempv;
9. Interrupts can be edge or level triggered.
· lcdcmd(OxBA);
MSdelay(50); 10. INTCON is used to �nable or disable the interrupts globi:tllY
sprintf(text,"%04dmv'',hexVal);
for(i=O;i<6;i + +) 11. Port B bits (RB0-2) are specifically used for detect any
{ interrupt. change.
lcddata(text[i]);
12. Capture : The CCP pin can be set as an input to record the
MSdelay(50); }
arrival time of a pulse. In this CCP module may use either
lcdcmd(OxCO); timer 1 or timer 3 w operate.
MSdelay(50);
for(i=O;i< 10;i + +) 13. Compare : The CCP pin is set as an output anq at a given
{ count, it can be driven low, high or toggled
'1
, ,
Microcontroller 5-52 Peripheral Support i11 P/C 18FXXXX Microcontroller 5-53 Perip/1eral Support i11 PIC J BFXXXX
14. Pulse Width Modulation (PWM) : Th� CCP pin is set as an PIR Registers
output and the duty cycle of a pulse can be varied. In PWM
The PIR registers· contain the individual flag bits for the peripheral
mode, either timer 2 or timer 4 may be used
interrupts. Due to the number of peripheral interrupt sources, there
15. The speed of the motor depends on three factors; load, voltage are two Peripheral Interrupt Flag Registers (PIRl, PIR2).
and current. For a given fixed load we can maintain a steady
PIR1 : PERIPHERAL INTERRUPT REQUEST (FLAG) REGISTER 1
speed by using a method called Pulse Width Modulation
(PWM). R/W-0 R/W-0 R-0 R·O R/W-0 R/W-0 R/W-0 R/W-0
18. Required reference voltages are obtained using ADCON 1. U-0 U-0 U-0 R/W-0 RIW-0 R/W-0 R/W-0 R/W-0
.. ., , ,.""1""""'·,...,,,""
f.............,.,. � r"""'..,..,.....,.._.,,..,..,,.... ....,f.......,""·........, . .....,..,.,.,.,."',.,,,,,,,._.,. ......, .... '\:
. .,..,_,��--.--....,., ,....,.� .
T
j
.,,.....,
.........� -
\
"''..,,.
19. ADCONO is used to select the required channel. il _ j - ! EEIF !; BCLIF ! LVDlF ( TM.R3IF CCP2IF
·' w-.�•�-'-w"-""' .,J ,,,._�,·-
. wm -'�'"·'"·-·"'- ' L ""=-w--.w J, ._"""-'�·•-"""'"''·'·"""'·''"""""'""
20. Sensors can be interfaced to PIC 18F4550 using ADC. bit 7 bit 0
T
w..w,v,w. •'·'"'.-.'•"
' ''•"
" '""° 1
' "'
i\ PSPIE1
11
j TXIE
, ,., ...
\ ccP1IE \ T!v1R2IE \ TMRllE
R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-x ...h ..... ..... ...
.. . . ., .... .....,.,, •••••,..,.•.,_ . . . . . .,,... ..
. ,.,.., .... ., •., ••,
. . ... ....,.. ... . .....,. ••• .,,..,.,., , .. ._, _ ,,.,... ,.... ,........, ............,.. ... . . . , ••.•••.••••, ..••••• .,.'"...... ,.,, ••."
). .,.,,., . . . .., ••., •• ., ••,. ••,....,••••••••
11rJ1[
1�1: c�i�;;���:1:·�i��;9·;�zJ�-i��i��.r;i�;�J:.�;����.I:����;�::L�i;,i�]::;:;i::J bit 7 bitO
l,';,j
:i!j1 bit 7 bitO
!� .
RCON REGISTER :
INTCON2 Register
1'
i,!I''
I) .
,:j,. R/W-0 U-0 U-O· R/W-1 R-1 R-1 R/W-0 R/W-0
R/W-1 R/W-1 R/W-1 U-0 R/W-1 U-0 R/W-1
1!.l: I
: :·:.:�!;���J���P.q\:�I:�;P.9�·:J::··;·.]:::���;-I:�:�::: :L��;::·,
1:1\t'' [�� ��=��I- -�I����=I�;I��·'·[���:�r:_;;]
..
!Hi" ITCON3 Register
flti
1�1: 1:
i I
R/W-1 R/W-1 U-0 R/W-0 R/W-0 U-0 R/W-0 R/W-0
bit 7 bit 0
,
i'j'� "' '--��1:.: [·�.:.'.:�- I�-��:.I:����I��-�-�::L���:.:I�"i���Iiiii�.�-�:J
I \ �
I!• ·
)�1 \.
bit 7 bitO
!lli = ·=�F"'-""""""""'______..__....,....,...,_____�;.;�;...
��I i 1
�1!�.i � A Gulde for Engineering St11dents
� - A Guide for E11gi11eeri11g S111de11ls
.
I
�I. •
'
h
·i
1�
Microcomrofler 5- 54 Perlpfleral Support i11 PIC IBFXXXX �-»:0:0-,.:.0.W��,:��
[§]
ADCONO register is used to set the conversion time and select the
Real Word Interfacing
channels. For power saving ADC feature is turned off when power
up. and turned on with ADON bit when required. GO/DOWN bit is with PIC18FXXXX '� I
t R/W-�
Q.1 Draw and explain port structure of PIC18 microcontroller with
��----·-·-·-··
·-,.
''''
.i - ,l --- 1. l l R/W-0
. different registers used in programming
.'l!��:l
'.� I
.. --1- f
CHS3 CHS2
L_ .
CHS! CHSO !JONE
r--··-'--L --·· _ ____
·--·
ADON
·-· ·-·-
R/W-0 1 R/W-011
r
t:-e- RJW'11
-
serial communication. Port pins are assigned with multiple task and
; - 1- - i
RJW'11
. U-0 U-0
-
R/W-0 RJW' 1
�
one of them will be available arid active at a time. All the functions
I .
VCFG I
!YCFGO PCFG3 .
PCFG2 PCFGI PCFGO
.
cannot be active simultaneously.
r.�-:-·· . --·---
-
bitO
• Some ports have 8 bits, while others may not.
L_7_______ ···········
• Each port has three registers for its operation
ADCON2 : AID control register 2 • TRISx register (Data direction register) : For most ports, the 1/0
The �CON2 register configures the . clock source, AID pin's direciion (input or output) is controlled by the data direction
programmed acquisition time and justification. After conversion register TRISx (x = A,B,C,D,E) : a. '1' in the TRIS bit corresponds
data in the ADRESL and ADRESH is right or left justified by to that pin being an input, while a ' 0 ' corresponds to that pin being
·r-�·----
ADFMbit an output.
�----,
PORT register :
------·· __.,._,_,,,___
,. ·
�FM i l
output. Reading PORTx register read the status of the pins,
------
� j ACQTO
-
·
-
'·I
Microco11tro/ler 6 2 Re"/ Word l11terj"ci11g witll PICIBFXXXX Mlcroco11troller 6 3 - Real Word l11terfaci11g wit/1 PICIBFXXXX
Upon reset all ports are configured as input-TRISx register has
port is configured as output. (Data transfer from data latch to port).
OFFh.
The data written may be 0 or 1.
The detailed structure of PIC port is shown in Fig. Q.1.1 with SFR's
• The . Port can be configured for read operation according to the
used for data and direction control.
setting of Direction. Control register Called as TRISx = OxFF i.e.
·
Reild/Write
__, Read po1t port is configured as input. (Data transfer from port to data lat. h).
The data read may be 0 or 1.
• During port read operation : TRISx = OxFF, RIW�l,
Port select 1, input buffer activated. by read
= port line signal,
write port and output buffer is disabled, Data from port pin either 0,
1 is placed on data line and stores in input data latch.
• During port write operation : TRISx = OxOO, R/W-0,
Port select 1, input buffer deactivated by read
= port line signal,
write port and output buffer is enabled, Data from input buffer is
placed on port pin either 0, 1.
I
/
I
I
,
Q.2 Draw and explain the port structure of PIC 18FXXXX for .
I ;I ;I'
writing 0, l to port pi�s.
J<l_,,/
1Dat:a SFR' / / ,/ ,.
Aris. Port structure for reading writing data
I I I I I I I :
( (].
The PIC18 family has five ports Port A (6), B (8), C (8), D (8), E (3)
I I I I I I with 33 VO lines. These lines can be used for data transfer between
'i)irection' SFR
working register 'W' and peripherals and vice a versa. Each port can
Fig. Q.1.1 Input I Output combined port structure
be configured as input or output. Each port has three registers for its
Each port in the PIC has three internal D flip-flops (latches) operation:
• Data latch to hold the output data • TRISx register (Data direction register) : For most ports, the I/O
• TRIS latch to setup data direction (Read or Write into or from the pin's direction (input or output) is controlled by the data direction
pin) register TRISx (x = A,B,C,D,E) : a IQ' corresponds 'to that pin
setting of Direction Control register Called as TRISx = OxOO i.e. output. Reading PORTx register read the status of the pins,
whereas writing to it will \\'f.ite to the port latch.
OFFh.
Zero ;1
• Each port in the PIC has three intemal_D flip-flops (latches) �
�
r-·-
·
,
' .
I
\� j,�.
ON
'
. 0 TRIS latch to setup data direction 4 '
TRIS=O+ o<
o Input latch for input data .............. TTt.CJ'
ij
u�
SCHMITT
trigger
The configuration of port for writing l or 0 to port pin is shown in
Fig. Q.2.1 and Q.2·.2. r
l
, Writing 0 to Port pin
Data latch output : Data bus = 0, Write port pin used to clock the Fig. Q.2.1 Output 'O' to pin in the PIC [writing]
r-RDLAT
data, Q= 0,Q = 1, OR gate= 1, P Gate= OFF, Port pin= 0
TRIS latch output : Data bus = 0, Write TRIS pin used to clock the -
.1Data bus
i
Y
TRIS Latch output : Data bus = 1, Write TRIS pin used to clock the TTLor
SCHMITT
Q = 1, AND gate= 0, N Gate= OFF port pin= 0
tngger
data, Q = 0,
'\ '
'
RD port
,:
! Microco11troller 6- 6 Real Word l11tetfaci11g witll PICIBFXXXX Microco111ivlfer 6- 7 Real Word l11tetfaci11g witll PIC18FXXXX
jI
Q.3 , Draw and explain the port structure of PIC 18FXXXX for Data latch oi..tput : Data bus = 0, Write port pin used to clock the
reading 0, l ·from port pins data, Q == X, Q =X, OR gate= 1, P Gate=OFF.
Ans. : Reading from port pin : The PIC 18 family has five ports Port TRIS latch output : Data bus = 0, Write TRJS pin used to clock the
A (6), B (8), C (8), D (8), E.(3) with 33 I/O lines. These lines can be
used for data transfer between working register 'W' and peripherals
and vice a versa. Each port can be configured ·as input or output. Each
data, Q "".'
�--<5=RD
1, Q =0, AND gate=0, NGate=OFF.
Vil
''l
f(
m·
•
to that pin being an input.
PORT register : The PORTx register is the latch for rhe da:a to be O�F fl
tth
���-
)�'[Ff\i output. Reading PORTx register read the status of the pins;
.1 .
y
�11.� ·'
whereas writing to it will write to the port latch. TRIS 1 •
OJC
= · 1 n1..., '�'-..,H
v,,
!ll;j l �RDTRIS
• LAT register (output latch) : The data latch register is useful for
ll!' read-modify-write operations on the value that the 1/0 pins are
0.
;
.
,.i)
!: � 0
;,�1t •
driving.
Upon reset all ports are configured as input-TRISx register has
\fll: ; RD port
: ,,:
OFFh.
11 , : ,'.·, Each port in the PIC has three internal D flip-flops (latches) Fig. Q.�.1 Input 'O' to pin in the PIC [reading]
,_,
•
ll11mIii'T Data latch to hold the output data Reading 1 from Port pin
i�IJ:
o
I
1m!i o TRJS latch to setup data direction TRlSx=OxFF port is configured as input.
l!lli..
IJH:
I•.,·,
o Input latch for input data Data latch output : Data bus.= 1, Write port pin used to clock the
!1,JIj{�';i \j • The configuration of port for reading 1 or 0 from port-pin is shown data, Q=X, Q = X, OR gate= l, P Gate=OFF.
Htl
!�'\ ;
'1•r: • in Fig. Q.3. 1 and Q.3.2. Data bus = 1, Write TRJS pin used to clock .the
TRIS latch output :
'i
!
Reading 0 from port pin data, Q= 1, Q = 0, AND gate=0, N Gate=OFF,
1:.1: TR1Sx =0 x FF port is configured as input Both the gates are off, hence data available on Port iine (0, 1) is
iil·<·i• .
I ;,,i ,
passed through the schmitt trigger and input latch.
l
1
i�l ': :!
� A Guidefor £11gi11eer/11g St11de11ts
� A G11idefor E11gilleer/11g Stmlents
;
',L,
Microcontroller 6- 8 Re"/ Word lnterf(lc/ngwit/1 PICJBFXXXX 6• 9 Re"l Word Interfacing witlt PICIBFXXXX
Microcontroller
- Vop
1�
One
N
OFF' R2 S20kn
'.
TRIS= 1 -=-
TILor
SCHMITT
trigger
C1
33 pF I -=-
-=-
RD port
1;
=
TRISBbits.RBO =
·. ' Fig. Q.4.1 LED Interfacing
Latch LATB O;
0;
=
LATBbits.LATBO Program:
#include <P18F458.h>
0
=
Port PORTx =
PORTB=OxAA;
MSDelay(250); c; l
rlri sw1
0.11,FT' �
} I
}
void MSDelay(unsigned int itime)
{
unsigned int i; tinsigned char j;
for (i=O; i<itime;i++)
VCC
for (j=O;j<lOO;j++); T Lo•cl
} .L .L . �· 1 G.1
Diocl•d t:1:1.oyct
Q.5 Write an embedded C program· to read status of SW connected
a3pF+
C1
l33pF C2
!R!'JI�)'
. : coil
at RDO and RDl. If RDO = 0 then Sl = 0 and RDl =. 0 the S2 = 1 fOK
.
.,,"fir -ONPN -- .
then: (a) If Sl = 0 then Relay on buzzer·off and LED wlll glow LSB !
GNDC::-
to MSB continuously. ,(b) If S2= 0 then Relay off buzzer on .and ·
��r�nE
LED will glow MSB to LSB. RS 01
"{W..
Ans. : Interfacing Diagram : The interfacing diagram for Switch, 3300 BC5•7AL
2
LED, Relay and Buzzer is shown in Fig. Q.5.1. �'.'.3R11
':"
Program: Spaa.ker
0hrn O<w
.... •
.
#inc!Ude<P18F4550.h>
void delay(void); Fig. Q.5.1 Interfacing of switch, LED, relay and buzzer
void main()
Sl =O;
{ if(PORTDbits.RDl = = 0)
unsigned char i, Sl,52;
S2 =1;
TRISB = OxOO; //LED pins as output
if(Sl == 0)
. LA.TB = OxOO;
{ // loop for relay on , Buzzer OFF, LED R-L
TRISDbits.TRISDO = 1; //set RDO as input
LATAbits.LATA.4 = 1;
TRISDbits.TRISDl = 1; //set RDl as input
LATDbits.LATD2 = 1;
TRISDbits.TRISD2 = O; //set buzwr pin RD2 as· output
for(i=O;i<B;i++)
TRISAbits.TRISA.4 = O; //set relay pin RA.4 as ou,tput
! {
while(l)
LA.TB = OXOl< <i;
{ delay();
LATDbits.LDO "':" 1;
LA.TB = OxOO;
LATDbits.LDl = 1;
delay();
if(PORTDbits.RDO "'= 0)
}
i
' . � A Guide for E11gilleerillg Students � A Guide for E11gilleeri11g St11de11ts
Microco11troller 6-11 Real Word Imerfaci11g witl1 PIC18FXXXX Microcolllroller 6-13 Real Word lnterfacillg witll P/CJBFXXXX
} for(i=O;i<S;i++)
if(S2 =''-" 0) {
{ II loop for relay OFF , Buzzer ON, LED L-R LATB = OXOl<<i;
'LATAbits.LATA4 = O; delay();
LATDbits.LATD2 = Q;. LATB = OxOO;
for(i=O;i<S;i+ +) delay();
{ }
LATB = OX80>>i; }
delay();
LATB. = OxOO; }
delay(); void delay()
} {
} unsigned int j,k;
} for(j =O;j <=lO;j+ +)
} for(k=O;k<=3000;k+ +);
void delay() }
{
Q,7 Draw a neat interfacing diagram to display 'SPPU' on 4th
unsigned int j,k;
for(j =O;j <=lO;j + +) position in line one and 'UNIVERSITY' at 5th position on second ·,,,,,
11::;j;j,,Is�.i�;�i/.·,
l,,,. ,,,
'..
,1';1';, Microco11troller 6 - 14 Re1tf Word l11teljf1cl11g i11lt/1 PIC18F)(}()(X Mlcroco11trol/er 6-15 Recr/ Word /11terf11cl11g wit/I PICJBFXXXX
'*:'f:
while(t)
�'·.:i ' ' {
lcdcm.:i(Ox84);
+ sv i
AI _L MSdelay(50);
-
n for (z=O;z<4;z++ )
r.;.· .
'l:'
.\:'
c3
o.1�1F
T
Dsw�
4
'
.{
lcddata(LCD_Datal [z] );
i
0
MSdelay(50);
5V
1
}
R2 20 kOh� lcdcmd(OxC5);
10 kOhm ·�ASdelay(50);
RI
"::'"
for (z=O;z<10;z++).
.
{
lcddata(LCD Data2 [z]);
_
C1 MSdelay(50);
33pFI }
}
- -
MSdelay(50); }
void lcddata(unsigned char value)
lcdcmd(OxOe); //Displ�y on, Cursor blinking
{ // Routine for Command word
MSdelay(50);
LCDPORT = v3.lue;
lcdcmd(Ox01); //Clear display screen rs = 1;
MSdelay(50); en= 1;
':'.��
�
:t:?,�
Microcontt'o/ler Mlcrocon troller
6 - 16 Real Word lntelfaclng wit// PICIBFXXXX 6 - 17 Real Word /11terfacl11g witfl PIC18FXXXX
i�
void MSdelay(unsigned. int itime) Program:
,,.,_
{ : ..:i
#include <p18f4550.h>
unsigned int i,j; #include "LCD_SIT.h"
• for(i=O;i<itime;i++) canst unsigned char LCD_Datal[J={"KEY="};
· for(i=O;j<1200;j++); canst unsigned char KeyLookupTbl[]= {'0','4','8','C',
} •11/51/9'/D',
Note : According to problem st tement, chang 121 161 1A1 1E'
� e the interfacing , 1 , 1
diagram and do changes in the program. 131,171 1B1 'F1};
1 ,
unsigned char get_keyval(unsigned char col, unsigned ch& row);
x
Q.8 Write an embedded C program for interfacing
of 4 4 matrix void main(void)
keyboard and display the number of key closed· on LCD. {
q" [SPPU ·: May-22, Marks 9,
g:
May-18, Marks 8, Dec.-17, Marks 8) unsigned char z=O,row,val;
Ans. : Keyboard interfacin TRISD= OxFO; //rows as inputs and cols as output
The interfacing diag.;arn of 4x4 matrix
keyboard ,is shown in Fig. Q.8.1. The microcontroll LATD= OxFF;
er a�.cesses both
lnit_LCD();
rows and columns through the port D.
lcdcmd(Ox80);
MSdelay(50);
for (z=O;z<4;z++)
{
' lcddata(LCD_Data1 [z]);
MSdelay(50);
, tL }
.... .---- ----·· · ·-·-- - -·--·· 1
.
1--���-���---t
·
i
·
while(l)
j
icu11
!jCol3
$W..=. $'A'3 I
C�l� Cul-4 {
. $W1 I SW4
............�E�.L.... ..
::� Ej Ci?=i c,�. .
LATD = OxFO;
J=
J �. v f
- .
MSdelay(5);
� · .
.....; .....;
-- · · ·
G:l
1
row= PORTO;
Cl
row>>=4;
if((row & OxOF)!= OxOF)
�""'*.
{
cj::
�'I '.
:1"
�.
�
!•:l··;..· :,
Microco11troller
lt�,,·�11,
6-18 Real Wort/ I11telfflci11g wit// PlClBFXXXX. Mit:roco11troller 6 - 19 Refll Wort/ I11terfaci11g wit// PIC1BFXXXX
ir{ I
} unsigned int i=O;
LATDbits.LATDl = 0; for(i=O;i<4;i + + )
' '
MSsielay(S); {
'
I:.
l1.
. row= PORTD; if((row & OxOl)I= OxOl)
\! . row>>=4; {
if((row & OxOF)I= OxOF) return(KeyLookupTbl[(col)+i]);
�i
{
·· 1
(' }
• val = get_keyval(4,row); else
'i
·�.�.' )I I
LATDbits.LDl = 1; row >>=1;
v-
�ll.1 } }
w
'
LATDbits.LATD2 = O; }
,,
MSde!ay(S);
Q.9 What ls the use of motion sensor ? Explain with classifications.
row= PORTD;
' ,lj·
LATDbits.LATD3 = O;
r ·
MSdelay(S); building· for monitoring the area around the building. Upon
·im�' I detecting motion, they generate an electrical signal based on which
.·
row = PORTD;
r· row >>=4;
:1 . some actions are taken. So.me operate in much the same way as a
li1·-
if((row & OxOF)I= OxOF)
military ra�ar scanner, while others work based on vibration,
{
val = get_keyval(12,row); infrared radiation and, even sound.
, i� ! .
LATDbits.LD3 = 1; • All of these different types of sensors have different strengths and
I i.' .! .
I Jii, }
.
1(,1•
MSdelay(lO);
�. :
Ii''
i
.} • Active detectors are also known as radar - based motion sensors.
"!''· The active detector sensors emit the radio waves I microwaves
• •
•' !
)i
.
}
across a room or other place, which strike on nearby objects and
·,
!' /*finds the value of the key• I
· ··jm111
· ...
. ::�·' · '.
Microco11tro/ler 6 - 21 Re"I Word I11terjaci11g witfl PICl8FXXXX H.
!!:!!CT'OCOllll:oller 6 - 20 Real Word Intetfaclng wltl1 PIC18FXXXX 1.;.;
;it!:.
• When an object moves ·in motion sensor controlled area at this • However, this technology also has its disadvantages. It cannot �\1/j
'!l:
time, the sensor looks for a doppler (frequency) shift in the wave provide the same level of safety as separate PIR anci microwave � ..
when it returns to the sensor detector, which would indicate that the sensors . because the alarm is triggered only when motion is �·
detected by both sensors. ,"11
. wave has hit a moving object. 'h
• Active motion sensors are not best suitable for outdoor lighting or • The motion sensors come in different shapes and sizes. Here we are
I
similar applications as a movement of random objects such as explaining below a couple of examples i
D
windblown things, smaller animals and even larger insects can be
Passive Infrared Detectors (PIR) : .i!l
·,,1
detected by the active sensor and lightning will be :riggered.
• These are one of the widely used sensors nowadays and can be
Passive detectors :
found in many home security
• Passive motion sensors are opposite to active sensors, they do not
systems. Passive infrared ·
send out anything, but it simply detects the infrared energy. ;, \:1
detectors are looking the
Infrared (heat)· energy levels are sensed by passive detectors.
changes of infrared energy
Passive sensors scan the room or area, it is installed for infrared
level that caused by
'\
the possibility of false alarm triggers. • Active infrared detectors use a dual beam transmission as structure,
• However, this technology also has its disadvantages. It cannot one side of a transmitter for t:mitting infrared ray and the other side
.• provide the same level of safety as separate PIR and microwave with a receiver for receiving the IR, it is suitable for the outdoor
·
sensors because the alann is triggered only when motion is ·point to point interruption detection.
detected by both sensors ..
• Active infra-red beam motion sensors are mainly installed outside, • Since the output of the PIR sensor module has .only two stages
due to it adopts transmitter and r.eceiver theory for detection. It is (HIGH (3.3 V) and LOW (0 V)), it can be directly interfaced to the
important that the beam must go through the detection area and PIC 18F4550 microcontroller.
reach the receiver. • The circuit diagram for interfacing PIR sensor to PIC l 8F4550
• :-hese motion sensors are available ·in both active and passive
types. -1n theory, an ultrasonic detector sends out high-frequency
sound waves that are reflected back to the sensor. If any
interruption occurs in the sound waves, the active ultrasonic sensor
+5 v
may sound the alarm.. The mini ultrasonic motion detector is shown
rW1
in Fig. Q.9.2. ' -=-
o�:J
+5 v
0
.,
�<3300
R3
I
I
MD1
S R4 �LED
R2 � 20 kOhni �10K
//
I
-..L
XTR1
33p�I I 33pF
•
}
Program
Q.11 State features of MQ-2 gas sensors. Draw an interfacing
#include <P18F4550.h>
diagram ·and embedded C code
#define _XTAL_FREQ 20000000 llSpecifythe XTAL crystal FREQ
Ans. : Features of MQ-2 Gas Sensor :
#define PIR RD2
#define LED RA4
• Operating voltage is +5 V
void TO'.:lelay(void);
void main(void) • Can be used to measure or detect LPG, Alcohol, Propane,
{ Hydrogen, CO and even methane
TRISA=OXOO;
• Analog output voltage : 0 V to 5 V
TRISD=OXFF
TRISA=OXOO; II Make all output of RA4 low • Digital output voltage : 0 V or 5 V (TTL Logic)
w�1ile(1) 11 get into infinite loop • Preheat duration 20 seconds
{
If (PIR==l) • Can be used as a digital or analog sensor
{ • The sensitivity of digital pin can be varied using the potentiometer
LED=l;
delay (); /I wait for some time Program
} #include<P18F4550.h>
else
#define _XTAL_FREQ 20000000 //Specify the XTAL crystal FREQ
{ #define GAS RD2
LED=O;
#define LED RA4
delay();. 11 wait for some time void delay (void);
} void main (void)·
}
}
·�
void delay()
{
unsigned int j,k;
�
}
I
; � R3
\ 1 f 330Cl ' Q.12 Explain use of IR sensor with various applications.
Ans. : IR sensors :
i
�
I
kOhm
R< 201 LED
R2 20 10K • IR sensor is an electronic device that emits the light in order to
J,
1,,
II
sense some object of the surroundings. An IR sensor can measure
fl.:· J_
the heat of an object as well as detects the motion. Usually, in the
infrared spe::trum, · all the
C1 C2
-::- types of radiations are
33pF
I T
33pF
invisible to our eyes, but
-=- -=-
'infrared sensor can detect
these radiations.
Fig. Q.11.1 Interfacing of MQ-2 Gas Sensor
• The emitter is simply an IR
rl: {
'
1" If(GAS==l)
LED (Light Emitting Diode)
it\'; { and the detector is simply an
"
u LED=l; IR photodiode . Photodiode is Fig. Q.12. 1 IR sensor
:,;
\i. � A Guide for E11gi11eeri11g Students
A Guide/or E11gi11eeri11g St11de11ts
t �
fli;:i
t.i'!
1i1,,
Microcontroller 6 28
• Real Word Interfacing wit/1 PIC18FXXXX Mlcrocolltroller 6 29
• · Real Word Interfacing wit// PICJBFXXXX
the IR LED. When IR light falls on the pbotodiode, t�e resistances ThP. microcontroller selected is PIC 18F4550 which works on the
and the output voltages will change in proportion to the magnitude frequency of oscillator ranging from 0 to 20 MHz and requires power
of the IR light received. supply of± 5 or±12 V. A simple circuit design for +5 V is shown in
Fig. Q.13.1
• There a�e five basic elements used in a typical infrared detection
system : An infrared source, a transmission. medium, optical '\
O_vd
��1
c � 05
l!4
'!805
VfC
component, infrared detectors or receivers and signal processing.
SVA�N! J>-- -
r------ - -- 1
Infrared lasers and Infrared LED's of specific wavelength used as -:;:- L co---
r T
c·g
100µF
J..
T
C10
0.1 pF
_L Ci1
T
0.11:F
. ' flndg�+
. T6BµF
..
infrared sources. ·
: !.'.��.]
.. ................._. .
*R. o4. 7 K
D3
· •. The three main types of media used for infrared transmission are �LED
vacuum, atmosphere and optical fibers. Optical components are
J_
used to focus the infrared radiation or to limit the spectral response.
Fig. Q.13.1 Sample for 9ower supply design i
Applications :
Step 2 : Design of clock circuit :
Night Vision Devices, Radiation Thermometers, Infra-red tracing, IT
image Devising. Other key application areas that use infrared sensors The Quartz crystal is connected to OSC 1 and OSC2 pin in order to
include: synchronize the operation of all components c9nnected with internal
and external means. The values for C 1 and C2 are selected according
• Climatology • Meteorology
to the crystal frequency for stabilizing the oscillator pulses. In general
• Photobiomodulation • Flame monitors with quartz crystal 22 - 33 µF is preferred.
• Oas detectors • Water analysis Step 3 : Design of reset circuit :
• Moisture analyze:s • Anesthesiology testing The RC high pass filter with C = O.lµF along with 20 kn register is
• Petroleum exploration • Rail safety connected to MCLR pin. When high pulse appear on it, resets the
contents of friter registers and SFRS to initial value.
• Gas analyzers
Step 4 : Configuration of port :
Q.13 Design a PIC 18 FXXXX based to tevt the LED, Buzzer and
relay connected to ports with control using keys. PIC has 33 l/O lines which can be configured as input and output
using TRISX register as
Q" [SPPU : May-22, Marks 9)
if TRISX = 0 - Ports (A-E) are configured as output ports
Ans. : Design of PIC test Board : Fig. Q.13.2 shows the design of
PIC test board for verifying the LED connected to port B, with ifTRISX = 1 ·Ports (A·E) are configured as input ports.
switches and buzzer to p9rt D, with relay interface for Port A.
....
A Guide for E11gi11eeri11g Swdents
:�����s A Guide. for E11gi11eeri11g St11de11ts �
%I
1 ., •
���
It
•
Microco11troller 6. 30 Rell/ Word b1te1fllci11g witfl PIC18FXXXX
Microco11troller 6 31• Rell/ Word I11tetfaci11g wltfl PJCJBFXXXX
Step 5 : Connection diagram
�0 Step 5 : Transfer content to port register
r· ,
�5 v
!!\i' I Step 6: Wait for some time i.e. delay
��··.'.0·
+5V
lu.j·.j
Step 8 : Continue Go to step 2
.l_ M
f'F·T
C3
4
SW1
.,____,_
di
�·.· o 1 Step 7 : Program :
�j i
�20
I ___ #include<P18F4550.h>
�.
�
void main()
�· {
L1
�!
� Crystal i
'1-
1 -=-
unsigned char i, key;
TRISB = OxOO; I/LED pins as output
LATB OxOO;
�· !
=
-�·.
__._
TRISDbits.TRISDl = 1; //set RDl as input·
�� while{1)
0 {
�!
,.',_' LATDbits.LDO = 1;
'
�·:
�'( LATDbits.LDl = 1;
iJ
if(PORTDbits.RDO 0)
Jr
= '=
1�1a11/
key =1;
�Speaker
if(key == 0)
-=-
.m��··1.·. ' {
Fig. Q.13.2 Minimum component test system I,ATAbits.LATA4 = 1;
,J
,Ji LATDbits.LATD 2 O;
';
Step 6 Algorithm
=
:
for(i=O;i<B;i+ +)
.J.11 I
Step 1 : Initialize TRIS SFR for direction control
{
i Step 2 : Check status of switch LATB ,,; OX01<<i;
Step 3 : If closed, load bit pattern to-glow LED, switch on buzzer delay();
·delay();
Step 4 : Otherwise wait till closer
}
Microco11troller 6- 31 Real Word I11terfacl11g wltl1 PICJBFXXXX Microco11tro/ler 6-33 Real Word Jnterfaci11gwith PICJBFXXXX
�
. ... ... . .i.· r;c-;·
{
h�, �·
05 IJ4
LATB = OXBO > >i;
*g;i,,F
7805
� . .
v_r:y
[L
delay(); ' -
_L
LATB = OxOO,: "
av ACl r- ·
8r.ag".J..
· ce
· ··
r
Cf!
100 �1F ·
c1�1
· 0.1 µF
delay(); + �.'(, T
�1
} 00
} �LEIJ
}
}
void delay()· Fig. Q.14.1 Sample for power supply design
{ • Reset: The RC high pass filter with C = 0.lµF along with 20 kn
unsigned int j ,k;
register is· connected to MCLR pin. When high pulse appear on it,
for(j =O;j < = 10;j ++)
· for(k=O;k<:=3000;k++); resets the contents of inter registers and SFRS to initial value.
} • PIC has 33 I/O lines which can be configured as input and output
using TRISX register.
Q.14 Design Home protection system for · indic ating various
parameters lil<e temperature, door open I closed, internal apparatus General block diagram
on, which will give alert by indicator, display and sounding alarm if
• The general block diagram of any security system without in built
exceed the set point. Also make provision to store few current
ADC is shown in Fig. Q.14.2 Some of the modern processor like
records in the serial memory for analysis. Q' [SPPU: 10 to 12 Marks]
PIC has the in-build ADC and require only signal conditioning
Ans. : Design of home protection system
circuit. The sample signal conditioning circuit is shown in
• The microcontrollcr selected is PlC 18F4550 which works on the
Fig.Q.14.3 The signal conditioning circuit for any analog signal
frequency of oscillator ranging from 0 to 20 MHz and requires
varies from signal to signal. For any low level signals an
power supply of± 5 or ±12 V. A sample circuit design for +5 Vis
Instrumentation amplifier is be�t choice.
shown in Fig. Q.14.1.
!, , .
6. Store the current records
�'
'1
·1
•
7. If everything is set right, continues from step 3.
'!·,
i
Fig. Q.14.2 The general block diagram
�\:
�;
�
R 1 S:
��! i.
D-f
.+i
�I
To CH 1
�f -::-
Algorithm:
\
.,
''!
·
6- 37
· .: ·'
6- 36
!
Microco11troller Reul Wordb1terfucing wit/1 PICIBFXXXX ' Microcontroller Reul Word I11lerfuci11g wit/I PICIBFXXXX
Complete schematic : The complete schematic diagram is shown in Important Points to Remember
Fig Q.14.5
1. Before interfacing any input/output device to microcontroller
refer to their specifications listed in data. sheets by the
manufacturers to fulfil the optimum wo!:"king conditions.
2. List the hardware and software requirements depends on type
of device to be interfaced.
3. Study the port structure of microcontroller to avoid damage to
its port pins. Refer to the Fan in and out conditions carefully.
4. Pull up resistors are required to avoid damage to port pins.
5. PIC18F4550 has Five port 9A,B,C,D,E - 35 I/O lines)' and
USB
6. Port B is m)ed for the external interrupts
Each port has multiplexed for many functions and some pins
are exclusively used as digital Input
;I; 1 .. 7. By default on power on reset all ports are configured as input.
I�.
1-+-
_i
-r-ww-j"
. . ....,. .1 �
NI ·'i
i
•1 �t �
1., ,!_fj i ! i
�1! "I! �l. �1 !
8. LEDs are most popularly used indication device. T.ake its
forward voltage into consideration which depends on its
I -
.
_) '! -ir �.
i_u...JI·�"f._)· '' colour composi" tion and calculate the value of current limiting
. ' k !'."
I i�I - . ---i ... l
__J
�+ t� LI
..
resistor using simply Ohm's law.
..
,�:11
�· I, .
t 1:.
L..�!··
9. LEDs can be connected in common anode or common cathode
configuration.
r """ '"':
�·-. '.�' 1.�,�,., .1,.
10.LCD is useful display device to display alphanumeric
.
I
•.... .
··�
�� ..
-i.'
1 characters with reduced power consumption.
l.·
! '
] I [
'-ii
J 11.RS- register select R/W read/write and EN are the important
. ...
.. .
io
i
10 jO j o
l !
\
' '.
I
•
io
�
l
1 !
...,,,. .- . .._. .
..
·� �
l
� �
introducing suitable delay.
� � � �
l,.. l l
> � �
character ;
\
I
i \
l ;
I
17.Key detection can be taken care by using look-up table l !
of ,
'
I
<
(
approach.
; !! characters
'
;
� � � j
l
� '
l !.
'
11
! l I
18.Motion detectors are type of PIR sensors ;
; �· ' ; i l I
�
\ ! ;
1
, I
! i !
F = 110; 5 10/5 7
1 i
'
� .
l
�
; !
l
I
�
1
�
l ;
19.Gas sensors are used in home protection system
;j l !\ l
j x
c
x
20. Wh1le designing any system make sure of VCC, GND, Reset
l. I l ! j
j__�-i
\
�-�-!?�
I
t,
S }_�� a _r� :::_� --" " .... . . �
\
L- i--t; �-l---i-�L--l
' '
_j
ll Write to character RAM ·
�l 0 i 0 j 0 \ I , Character address ,
____ __
..
!
and clock is connected ;
\ ' ! l ' i
, . ,J
.
; L
-
'"'"""""··--···---L��::5.5.,.�.�t!:_�-�::.���-��: .
.
�
l 1 j' Display data address
,
, .. , -� l.
li 0 j 0
. �. .. '
t
···
... ,,. J
!
i
LCD commands framing 'l
l · !
.\
.,...op,w,... .. -::·M···""'""''i'"'"
· ,...,.. ...._._.,...
.
i D6 � D5 ! D4 \ D3 \ D2 Dl l DO i
'{,...'"""'""0..:•: '""'""'"'"'<"''M.,...,..,W�-...... ......
I
.. """''W·V.W.V.'"""i.
......,.,,.,,...,....w,...,,,,,.,.,.,.,(YY""'"""..........,.,
· ·· .j I ' i
1
. . .. ·
�-���·;·�':·� '; ���·:�:. .· ····'""'.·
BIT RS \ R/W \ D7
·- - - - ·
.
1 .
··, · · · '··1··�·- i'·�-"T"�� L ��=nt a::��,,. ; � \·;
'
\
.
, . ,. . . . , .
--�,,----�l- . . -- + -
. �
.
--j
..
; I I i I I l i I
0 0 0 0 0 0 0 0 j 0 ! 1 Clear LCD and memory, home I
,
.,
C�ara���----�.---·--l·'!!_ -���?,.��;-�.:�::!�, .i!.'
, ,
.
.,, ...-,..,,,.,._
. . .
· rite
i · ·····""····f""•'"""!..
I .
,,,,_ �- -=· .. ... . . .._,................... . .. . . . .. .. .. .. .. .. .
l \ :i
.
l
1 i \ \ 1 t
l !
·
!
\ ; l \
�
\
l I ; 110 ! S !' Screen action as display ;
.... .. ·
.... ..
...,,.,.,.,.,.,.,.,.,...,,,.,,,..,...,.,....,,..,.,..,,.,.,.,....,....._,,.,....,,_...,....,,.,.,.J.
�
·
. .� � { . �
j
i \ 1 character wntt�n
� � l � )
;
i
\ !l \: l
! ji !1 \1 ! ! END
ll
) j l S = 110 : Shift screen/cursor
l \ ilS
l i ; 1 ;
�
;
�
\ 1 .
...
i i ' �� l: 'i· 1!
:
l i' \
�
VO= 110: CursorR/L,
� � �; � � j �
•
�
�
j
� � <
� ... 1"� l ...,.........r,..�. , ]''M>"
�f... .... :�,, ....... wr
.w.•,• .... ,....,... M
� ('<'-W" """·l� .... '" ... .,..,,,�, �
�
.JI...:.screen L/R,w.WYNNNJ,,.,...,_WWWNM
�
...
i I }
T
,
..
i � : �
Ii ' !i �i C = 110 : Cursor on/off
.
� � . � ' �
� � -
j
�. },
.
�
.
� � 1
. .
:
! I l ! B = 1/0 : Cursor
� � j �
!
: l. ..-w.·.,- ; .. \ \ .. . , ""i""""" ---..
.,..,......... wo.•MWMN.,·. . ·
'
...• _,,,,,.,. .., .,.,,...,,.,. ..,_.w,,.•.,
I t
"'"''"'_"}
wwo ·-� -
Bhnk
'
I Noblmk �
( '
.
'""'�""""--·--""·-·� ""'
•
" '-'"""'
11
.:
I
l"""'',..._,._""1
UnitV�
"""' Microcolllroller 7- 2 Serial Port Programmi11g a11d l11terfaci11g witlt PICI BFXXXX
,j
• PC standardbaud rate (see hyper terminal configuration)
150, 300, 600, 1200, 2400, 4800, 9600, 14400,. 19200, 2_8800,
[ZJ
33600,57600
Serial Port Programming a!id
Interfacing with PIC18FXXXX
- - --- - -liitertace-ca'bie- - - - - --
--------------- ---------
Q.1 Stat.e features o( RS232 with signal characteristics and frame
format Bai" [SPPU : Marks 8)
Ans. : RS232 serial port : RS232 is an asynchronous serial
Fig. Q.1.1 Serial communication
communication protocol widely used in computers and digital
systems. - It is called asynchronous because there is no separate • It uses DB9 or DB25 connector to interface the PC serial port with
synchronizing clock signal as there are in other serial protocols like external devices as Data Terminal Equipment (DTE) and Data
SPI and I2C. The protocol is such that it automatically synchronize
Communication Equipment (DCE).
itself. It has following features
• The RS-232 interface works in combination with UART universal
• Developed by Electronic Industry Association (EIA) in 1960 and
asynchron�us receiver/transmitter. It is a piece of integrated circuit
updated in 1969
:�
integrated inside the processor or controller. It takes bytes and !
• Most widely used serial l/O interface standard asynchronous I�
transmits the -individual bits in a sequential fashion in a frame as
communication [TxD ,RxD and GND]
shown in Fig. Q.1.1.
• Accepted to transfer characters over short di&tances of 50 feet. iif
'. i\·
for an
• Low data rates - kbps Signal characteristics of RS232: This is the equivalent circuit
either the DTE
• Input and output voltage levels are not TTL compatible. EJA232 signal line and applies to signals originating at
in the standard,
or DCE side of the connection. "Co" is not specified
• Logic l : -3 to -25 volt - Negative logic.
elements only.
but is assumed to be small and to consist of parasitic
• Logic 0 : 3 to 25 volt
does not
"Ro" and "Vo" are chosen so that the short-circuit current
• Can operate in a full duplex manner, supporting concurrent data
the standard;
flow in both directions. exceed 500 mA. The cable length is not specified in
less than 25
acceptable operation is experienced with cables that are ::1
• MAX 232 IC is normally termed as line drivers.
feet in length as shown in Fig. Q.1.2.
. AI
• It is designed around transmission of characters (of 7 bits of
length). Sends each bit in exactly the same length of time
�: Microco11trol/er .. 7• 3 Serial Port Programming mid Iiiterfacing witll PICJ BFXXXX 7• 4 Serial Port Programmi11g and I11terfaclng wltlt PICJ 8FXXXX
� Microcoiltroller
�i�·
�
Interface
/ -u
points
�' <50 Ohms 3 • 7 kohms
. Ans. : RS485 Protocol :
i
1
Ro
N'
\.w !
RL
Silent features
' T <·
-�------- •
i
.
5 ·
' . 1. Uses balanced differential configuration with Multi-drop.
1 Vo _LcL '
j. C c ble l
I"< 2500 p F ..·�v 2. Has 32 line drivers and receivers, can extend up to 256.
± 25 v' -
·
OT - -·
< -=-<
J
J
.�
j
� - -- � -- - - .....:Gl) 3. High data speed: 35 Mbit/s up to 10 m and 100 Kbit/s at 1200 m.
Pin 7. Ground ! Pin 7, Ground
Generator RS-485, is a standard defining the electrical characteristics of
Receiver
•
systems.
Fig. Q.1.2 Signal characteristics of RS232
• The standard is published by the ANSI Telecommunication
The frame format used for communication is shown in Fig. Q.1.3.
Industry Association/Electronic Industries Alliance (TIA/EIA).
The transmission rate of serial devices is called baud. It is the number
• Digital communications networks implementing the EIA-485
of changes in the signal per second - Baud rate is the important
standard can be used effectively over long distances and in
property of any serial communication.
Receiver samples data i11 ce11ter of bit time electrically noisy environments.
'jf
·!i1'·
!i
!die state _J J J J J J.. J J__ !die state • Multiple receivers may be connected to such a network in a
L:._ .. � _; : : : 5_ _; __ : ; :
__ __ __ __ __ __ __
: !' I 1 I I I 1 I
2 3 _4_ .. __ e__ 1 a
linear, multi-drop configur�tion. These characteristics make
fl,
Start bit
·- _ _ .. __ __
Data bits
_ __ __ __ __
;)J.• ._ Minimum of .
one stop bit
such networks useful in industrial environments. and similar
�.<11i•¥�· Bit time = 1.
t- applications.
r
Jt,
r.il'r j''; Fig. Q.1.3 Asynchronous frame format EIA-485 enables the configuration of inexpensive local
'li •
!1..,I
'•1 networks and multi-drop communications links. It specifies
�)! Asynchronous serial transmission is widely used for the character
electrical characteristics of the driver and the receiver. It does
oriented transmission. It has the speed limitations due to the fact that
r' not specify or recommend any data .Protocol.
J: RS-232 is analog, therefore it is slo� (in computing terms). The
IfI Computer-baud rates : 110, 300,600, 1200, 2400, 4800, 9600, 19200
• It offers high data transmission speeds (35 Mbit/s up to 10 m
and 100 kbit/s at 1200' m).
etc
• Since it uses a differential balanced line over twisted pair it can
Q.2 State features of RS485 with network topology used in span relatively large distances (up to 4000 feet or just over
communication. � [SPPU: May-19, Marks SJ ' 1200 meters).
�
t A G11i<le for E11gi11'eeri11g St11de11ts
�
"
. A G11idefor £11gi11eeri11g St11dents
',,,
I
.' �
Microco11trol/er -
7 5 Seri"/ Port Programming a11d l11terfctci11g witfl PTCI BFXXXX ·Microcontroller -
7 6 Serial Port Pr?grammi11g cmd lnterfctcing witfl PICI BFXXXX
• EIA-485 drivers need to be put in transmit mode explicitly by • Network topology is probably the reason why RS48� is now the
asserting a signal to the driver. favourite of the four mentioned interfaces in data acquisition and
control applications.
• The equipment located along a set of EIA-485 wires are ·
I
• The RS485 network must be designed as one line with multiple
• .And that with an interface which does not require intelligent
drops, not as a star. Although total cable length may be shorter
network hardware: the implementation on the software side is not
in a star configuration, adequate tennination is not possible
·
much more difficult than with RS232.
I
1
anymore and signal quality may degrade significantly.
• It is the reason why RS485 is so popular with computers, PLCs,
micro controllers and intelligent sensors in scientific and technical
applications.
';<J_txL����
�-, -1 -,-'--t: ',
Twisted pair cabie
:;t
It is typically used for attaching low"·r-speed peripheral !Cs to
''!.
,j
•
.·{
\
�
i
SCL
--:;-
Q.4 Explain in depth use of 12C protocol with features Fig. Q.4.1 Connection to serial devices on 12C bus
either a transmitter (Master) or receiver (Slave). • No limit on the number of bytes transferred
• A master is the device which initiates a data transfer on the bu3 and • Has clock synchronization.
generates the clock signals to permit that transfer. At that time, any • Transmission speed : Normal : 100 kHz, Fast mode: 400 kHz and
device addressed is considered a slave.
HS-mode: 3400 kHz.
• Both SDA and SCL are bi-directional lines and connected to a • Maximum bus length of 4 meters.
positive supply voltage via a current-source or pull-up resistor.
• Maximum drive capacity of 400 pf.
• W�en the bus is free, both lines are ffiGH.
• Real multi-master capability.
• Devices-connected to the b:Js must have an open drain or open
• Compatible with most IC technologies (TTL, CMOS, etc.).
collector output for serial clock and data.
·I'' • Has arbitration procedure.
i'
I
• I2C is a synchronous serial bus protocol
?!
:I \
� A Guide for Engi11eeri11g St11de11ts � A Guide for E11gineeri11g S1111ients
1·
,,
I�
'Ii�
Microco11troller 7 -9 Seri"/ Port Progr"111111/11g a11d Jntetj'acl11g witli PIC1 BFXXXX Microco11troller -
7 I0 Seri"/ Port. Programmi11g a11d /11teifaci11g witlt P/Cl 8FXXXX
• Two wires, serial data (SDA) and serial clock (SCL), carry • STOP data transfer : A change in the state of the data line, from
information between the devices connected to the bus. LOW to IIlGH, while the clock line is IIlGH, defines the STOP
• Each device is recognized by a unique address and can operate as condition.
either-a transmitter (Master) or receiver (Slave). • Data valid : The state of the data line represents valid data when,
• A master is tpe device which initiates a data transfer on the bus and after a START condition, the data line is stable for the duration of
generates the clock signals to pennit that transfer. At that time, any the IIlGH period of the clock signal. The data on the line must be
device addressed is considered a slave. changed during the LOW period of the clock signal. There is one
clock pulse per bit of data.
• Both SDA and SCL are bi-directional lines,
The data on the line must be changed during the LOW period of
Connected to positive supply voltage via· a current-source or
•
• a
the clock signal. There is one clock pulse per bit of data.
pull-up resistor.
o Each data transfer is initiated with a START condition and
• When the bus is free, both lines are IIlGH
terminated with a STOP condition.
• DeviCes connected to the bus must have an open drain or open
o The number of data byte� transferred between START and
collec�or output for serial Clock and data
STOP conditions is not limited, arid is determined by the master
Q.5 · Explain Operation of 12C protocol with Start, Stop, data valid device.
condition etc. and device addressing for data transfer . o The information is transferred byte-wise and each receiver
Ans. : 12C operation for Data Transfer: acknowledges with a ninth bit.
• Data transfer can be initiated only when the bus is not busy. o Within the I2C bus specificatjons a standard mode (100 kHz
clock rate) and a fast mode (400 kHz clock rate) are defined. ,·i.
• During data transfer, the data iine must remain stable whene:ver the ,
.rr�
the acknowledge clock pulse in such a way that the SDA line is '[>
:1!
j.:11
(':: :· �- �·_;;' J
A Guide j 'E11gi11et:(i11g St11tle11ts
� A Guide for E11gi11eeri11g Students
·l:,ji
Microco11troller 7 - 11 Serial Port Progr"mmi11g a11d l11teefac/11g wltlr PIClBFXXXX · Microco11troller 7-12 Serial Port Pr(>gra111111i11g tmd ll1teefaci11g witlr PICIBFXXXX
stable LOW during the HIGH period of acknowledge related clock S = Start Condition, RJW = Read I Write, A = Acknowledgement,
pulse. P =Stop
• N number of data can be transferred. between start and stop '
Q.6 Compare SPI , 12C and USART protocols.
conditions.
Ila" [SPPU: Nov.-15, May-16, Marks 8]
• The detailed sequence of data transfer and initial conditions are
Ans. : Comparison between 12C and SPI : The comp�rison between
shoWI1 in Fig. Q.5.1, Q.5.2 and Fig. Q.5.3. synchronous and asynchronous protocol is given in Table Q.6.1.
Stop:
. Data valid :
SCI.· High·
when S�L is high
SDA· L·H
Read data
'
i1l
\:
··1?.
.:"
fi(
M/crocolltrolfer 7 - 13 Serial Port Programmi11g and Interfacing witll PICJ BFXXXX Microco11troller 7 - 14 Serial Port Programmi11g <111d I11teifaci1.•g wit/1 PICJ BFXXXX
Q.7 Draw' and explain the block diagram of MSSP, SPI mode in 3. Serial Receive/Transmit Buffer (SSPBUF) - Utilized which
detail. S" [SPPU: May-16,17, Dec-17, Nov.-15,16, Marks 8, data bytes are written to or read from controller.
May-22, 9 Marks ]
4. MSSP Shift Register (SSPSR) - Not directly accessible :
Ans. Master Serial Synchronous Port (MSSP) - SPI bus :
SSPSR is the shift register used for shifting data in or out.
:
microcontroller devices. These peripheral devices may be serial double buffered receiver. When SSPSR receives a complete byte, it
EEPROMs, shift registers, display drivers, ND converters, etc. is transferred to SSPB � and the SSPIF interrupt is set.
• The SPI mode allows 8-bits of data to be synchronously
• During transmission, the SSPBUF is not double buffered. A write
transmitted and received, simultaneously. to SSPBUF will write to both SSPBUF and SSPSR.
Serial Clock (SCK) - RC3/SCK/SCL/LVDIN 3. Clock for shifting the data in and out.
be used when in a Slave mode of operation) 1. When initializing the SPI, several options need to be specified. -ii
This is done by programming the· appropriate control bits
'l
The MSSP module has four regi_sters for SPI mode operation. I
(SSPCON1<5:0>) and SSPSTAT<7:6>. These control bits
•
These are: I
!i
:·::::��? A
� A G11idefor E11gi11eeri11g Stude11ts
Microco11troller 7 -15 Serial Port Program111i11g tmd J11terfacing wltfl PICJBFXXXx Microcontroller 7-16 Serial Port Progra111111/11g tmd 111teifaci11g witli PJqBFXXXX
/,,......w.........,... ..,,Y,WNW.WMJ>W·'•'"'MY>W••Y'o.........w
. ... Yf'oWuwwn.....wMY�U• MV.WH.',W....WMw.;,,
... .,,
I
,
transmission/reception of data will be ignored, and the write
collision detect bit, WCOL (SSPCONl<7>), will be set.
I
determined if the following write(s) to the SSPBUF register
completed successfully.
I
the various status conditions.
I
''i ·
..,
v.
• The MSSP module in I2C mode fully .implements an master and
l slave functions arid provides interrupts on start and stop bits in
!
hardware to determine a free bus (multi-master function).
:t!
Microco11troller 7-17 Serial Port Programmi11g a11d ll1terft1cl11g witlt P/C18FXXXX Microco11troller 7 18
- Serial Port Programmi11g a11d /11terft1ci11g wit/1 P/Cl BFXXXX
• According to the I2C specification, all changes on the SDA line · • The lower 6 bits of the SSPSTAT are read only. The upper two bits
must occur while the SCL line is low. Th!� restriction allows two of the SSPSTAT are read/write.
maique conditions to be detected on the bus; Start and Stop • SSPSR is the shift register used for shifting data in or out. SSPBUF
• ·A START sequence occurs when the master device pulls the SDA is the buffer register to which data bytes are written . to or read
line low while the SCL line is high. from.
SSPADD register holds the slave device address when the SSP is
The I2C protocol also permits a Repeated Start condition (RS),
•
•
without preceding it with a STOP·sequence • When the SSP is configured in master mode, the lower seven bits
of SSPADD act as the baud rate generator reload value.
A. 12C Bus registers
• In r�ceive operations, SSPSR and SSPBUF together, create a
• The MSSP module has six registers for I2C operation these are : double buffered receiver. When SSPSR receives a complete byte, it
• MSSP Cont�ol Registerl (SSPCONl ) is transferred to SSPBUF and the SSPIF interrupt is set.
•
�7 �o
slave ±Unctions and provides interrupts. on start and stop bi.ts in
MSSP Status Register (SSPSTAT)
hardware to determine a free bus (multi-master function).
•
'
Microco11troller 7-19
JI Serial Port Programmi11g <md Inte1f
aci11g witll PICJ 8FXXXX Microcoiirroller 7 • 20 Seria/PortProgra111i11i11g cmd lllte1f11ci11g wit// PICJ 8FXXXX
I,;
Ii;
[i' .(SSPCONl <3:0>) allow one of the following I2C modes to be proper operation of the module, pull-up resistors must be provided
,ii
qj
i<I selected: externally to the SCL and SDA pins. A simplified block diagram
; .: ofl2C mode is shown in Fig. Q.9.1. .
J'! o I2C Master mode, clock
:.1.
.,i·i' o I2C Slave mode (7··bit address)
• In Slave mode, the SCL and SDA pins must be configured as
inputs (TRISC<4:3> set). The MSSP moduie will override the
,,
:·j
I2C Slave mode (7-bit address) with start and stop bit interrupts
The I2C Slave mode hardware will always generate an interrupt on
o
•
enabled
an address match. Address masking will allow the hardwar� to
!:�
o I2C Slave mode (10-bit address ) with start and stop bit generate an inten·upt for more than one address (up to 31 ih 7-bit
,�, interrupts enabled addressing and up to 63 in 10-bit addressing).
t�· .
_,/'•"''""..,'•""''.'''""·'"'....,•"'•'•WMW...,w.w,•,,.,,.w,,.,,.,.....,.,.,.,�w...,.,._.,,...,.,..,"'w.'"..........,.WhY..,.W....,w,.,...,w... .,..... w,,\
Through the mode select bits, the user can also choos� to interrupt
,.__
•
� $W7rmm= lnt�1 nal diiita bt..<.1\
p· on start and stop bits. When an address is matched, or the data
.�
load the SSPBUF register with the received value currently in the
SSPSR register.
�
�!r • Any combination of the following conditions will cause the MSSP
� module not to give this ACK pulse :
I; :
�! Ad:-.;tr ff:<-W�h • The Buffer Full bit, BF (SSPSTAT<O>), was set before the transfer
;:
was received.
�·,.
• The overflow bit, SSPOV (SSPCON1<6>), was ser before the
t
�
I, transfer was received.
I�
In this case, the SSPSR register value is not loaded into the
. , •
�
., ,
,,, ,. .
. .-,w,--.,..,,..,..,.,.,. , ..,_...,"<W;.-.w,..._,,_,..,,,..., ,,,,_HW'''
software.
(il
:t
. Fig. Q.9.1 12C block diagram slave mode
• Once the MSSP module has been enabled, it waits for a start
• I2C Finnware controlled master mode, slave is Idle Selection of
· condition to occur. Following the start condition, tbe 8 bits are
any I2C mode with the SSPEN bit set forces the SCL and SDA
.
"; I:'' shifted into the SSPSR register. All incoming bits are sampled with
.
;. ;:
0
pins to be open-drain, provided these pins are programmed as
·the rising edge of the clock (SCL) line. The value of register
f.11 inputs by setting the appropriate TRISC or TRISD bits. To ensure
i::I SSPSR<7:1> is compared to the value of the SSPADD register.
1:11
t-!
f::)
� A Guide for E11glneeri11g Students �. A Guide for E11gi11eeri11g St11dents
� "'•·
j
J
.,�
Mlcroco11tro/ler 7 - 21 Serial Port Programmi11g mrd l11teifacing witlr PICI BFXXXX BFXXXX
Micro.::011troller · 7 - 22 Serial Port Programming and Jlllerfacing witll PICI
The address is compared on the falling edge of the eighth clock is set or the
Control of the I2C bus may be taken when the P bit
•
•
(SCL) pulse. If the addresses match and the BF and SS.POV bits
bus is Idle, with both the S and P bits clear.
are clear, the following events occur :
• In Firmware Controlled Master mode, user code conducts all I2C
1. The SSPSR register value is loaded into the SSPBUF register. bus operations based on stru.1 and stop bit conditions.
2. The Buffer Full bit, BF, is set. • Once master mode is enabled, the user has six options :
3. An ACK pulse is generated.
1. Assert a start condition on SDA and SCL.
4. The MSSP Interrupt Flag bit, SSPIF, is set (and interrupt is
2. Assert a repeated start condition on SDA and SCL.
generated, if enabled) on ·the falling edge of the ninth SCL
of data
pulse.
3. Write to the SSPBUF register initiating transmission
I address.
• Reception : When the R/W bit of the address byte is clear and an
4. Configure the I2C port to receive darn.
address ·match occurs, the R/W bit of the SSPSTAT register is
d
cleared. The received address .is loaded into the SSPBUF register 5. Generate an acknowledge condition at the end of a receive
and the SDA line is held low (ACK). byte of data.
• Transmission:· When the R/W bit of the incoming address byte is 6. Generate a stop condition .on SDA and SCL.
'set and an address match occurs, the R/W bit of the SSPSTAT • The following events will cause the MSSP Interrupt Flag bit,
register
'
is set. The received address is loaded into the SSPBUF SSPIF, to be set (and MSSP interrupt, if enabled):
.
register. The ACK pulse will be sent on the ninth· bit and pin tted
• Start condition, Stop condition, Data transfer byte transmi
RBl/ANlO/INTl/SCK/SCL is held low regardless of SEN.
I received, Acknowledge transmit, Repeated Start.
Q.10 Draw and explain the block diagram of MSSP, 12C Master • Fig. Q.10.1 Shows the MSSP I2C master mode configuration.
mode in detail. Qr [SPPU: Nov.-16, Marks. 8] (Refer Fig. Q.l 0.1 on next page)
Ans. : · MSSP 12C Master Mode
Operation of master mode : :·:
SSPM.bits in SSPCON l and by setting the SSPEN bit. T,n Master or with a
and stop conditions. A transfer is ended with· a stop condition
mode, the SCL and SDA lines are manipulated by the MSSP also the
repeated start condition. Since the repeated start condition is
hardware if the TRIS bits are set. released.
begir..ning of the next serial transfer, the I2C bus will not be
while
Master mocie operation is supp0rted by· interrupt generation on the In Master Transmitter mode, serial data is output through SDA,
•
detection of the start· and stop conditfons. The Stop (P) and "
Start (S) bits are cleared from a Reset or wlien the MSSP module is
disabled.
2. SSPIF is set. The MSSP module will wait the required. start
: IS time before any other operation takes place.
��
-� � 3. The user loads the SSPBUF with the slave address to transmit.
"-u- � ,
8 \l
�� 4. Address is shifted out the SDA pin until all eight bits are
M !! ·G
v transmitted.
�l
r��<Jr:.�����:-§,��i��;ii��="
;
I ' 5. The MSSP module shifts in the ACK bit from the slave device
:
·
�-i� SCL outputs the serial clock. The first byte transmitted contains the 8. Data is shifted out the SDA pin until all �ight bits are
u slave address of the receiving device (seven bits) and the Read/Write transmitted.
il
(R/W) bit. In this case, the R/W bit will be logic · o· Serial data is 9. The MSSP module shifts in the ACK bit from the slave device
·
II .
address followed by a ' 1 ' to .indicate the receive bit. Serial data is .
received via SDA, while SCL outputs the serial clock. Serial data is 1 2.Interrupt is generated once the Stop condition is complete.
received eight bits at a time. After .each byte is received, an
Acknowledge bit is transmitted. Start and Stop conditions indicate the Q.11 Explain the use of BRGH register for calculation of Baud
beginning and end of transmission. The baud rate Generator used for rates in USART . .u:i> [SPPU: May-22, Marks-9, May-17 ,18, Dec.-18, Marks 8]
the SPI mode operation is used to set the SCL clock frequency for Ans.: USART Baud Rate Generator (BRG)
either 100 kHz, 400 kHz or 1 MHz 12C operation. • The BRG is a dedicated 8-bit, or 1 6-bit, generator that supports
both the asynchronous and synchronous modes of the U�ART. By
.
default, the BRG operates in 8-bit mode. Setting the BRG 16 bit
(BAUDCON<3>) selects 16-bit mode. .
• It is a dedicated 8-bit baud rate· generator. The SPBRG register
controls the period of a free running 8-bit timer. In Asynchronous
mode, bit BRGH (TXSTA<2>) also controls the baud rate.
• Calculation of baud rate for different USART modes, which only
apply �n master mode (internal clock).
• The data on the RC7/RX/DT pin is sampled three times by a
majority detect circuit to determine if a high or 'a low level is
present at the RX pin. For example
1' Fosc= 10 MHz, Desired Baud Rate= 9600, BRGH= 0, SYNC= 0
• Given the desired baud rate and Fosc, the nearest integer value for
the SPBRGH : SPBRG registers can be calculated using the:
equation 1. From this, the error in baud rate can be detennin.ed. An
example
[ 156250 I 9600 ] 1
''•"<o -·· rno.wwwo .
Q.12 Find the value to be JQaderl into SPBRG register for baud rate
=
It may be advantageous to use the high baud rate (BRGH= 1) even for " Ans. : Value to be loaded in SPBRG register for BR of 1200 is
slower baud clocks. This is because the Fosc/(16(X + 1)) equation can
BRGH=O
X = [Fosc/ (Desired baud rate
reduce the baud rate error in some cases.
x 64)] - 1
Writing a new value to the SPBRG register causes the BRG timer to
[156250 I Desired BR]-" 1
be reset (or cleared). This ensures the BRG does not wait for a timer 'I
(156250 I 1200] - 1
I
overflow before outputting the new baud rate.· The calculation of low
and high baucl rate is shown in Table Q.11.1 =
(129)10 = (81)16.
�
- ·· �
-2-_.:__��- :.:/·
--· . �
A Guide for E11gi11eeri11g Stm!l!llts A Guide for E11gineeri11g Students
'"
�1
ji
I:
1:
I!
I!
Microco11trol/er 7 - 27 Serial Port Progr"mmi11g a11d I11terfaci11g with PIClBFXXXX
!) o
!t
= [625000 I Desired BR] - 1 duplex), Synchronous - Slave(half-duplex)
l
1 R/W-0 R/W-0 R/W-0 Riw-0 R/W-0 Rlw-0 R/W·"l R/W-0 !
CSRC l TX9
Q.13 Expla in concept of USART trans· receiver with TXSTA and
RCSTA regisers.
I bit 1 bit 0 !i
L.., .;,_,,
__ ______________ ,.,. .,,,,;
Ans. : Universal asynchronous receiver transmitter
Transmit control register (TXSTA)
• The Universal Sync�onous Asynchronous Receiver Transmitter
2. Receive Status and Control Register (RCSTA) :
(USART) module is one of the two serial I/O modules. _(USAR
T is It is 8 bit register, used to enable the serial port to receive data.
also known as a Serial Communications Interface or SCI.) .·
��---------��-"'!
• The USART can be configured as a full duplex asynchr R/W-0 R/W-0 R/W-0. R/W-0 R/W�o R-0 R·l R-x j
onous
system that can communicate with peripheral devices, such as
Q.14 Draw and explain block diagram of USART Transmitter • · Polling TXIF immediately following a load of TXREG will return
Q' [SPPU: Dec-18, May-17,18, Marks 8] invalid results.
Ans. : USARr Transmitter
• While TXIF indicates the status of the TXREG register, another
• · The USART transmitter block diagram is shown in Fig. Q.1 4.1 bit, TRMT (TXSTA<l >), shows the status of the TSR register.
The .heart of the transmitter is the Transmit (Serial) Shift Register TRMT is a read-only bit which is set when the TSR register is
(TSR). empty. No interrupt logic is tied to this bit so the user has to poll
• The shift register obtains its data .from .the Read/Write Transmit this bit in order to determine if the TSR register is empty.
in software. i1z1£��re1
• The TSR register is not loaded until the stop bit has been _I� _J '
!
9
transmitted from the previous load.
l
i t
• As soon as the stop bit is transmitted, the 'rSR is loaded with new I
•i ;
l\�:ff�.B.®.Ng(
•
data from the TXREG register (if available).
Once the TXREG . register transfers the data to the TSR register
Interrupt
TXEN
Baud rntfi Cl.KE TXfi
(occurs in one ICY), the TXREG register is empty and the TXIF rr�,·
Baud rate generator
flag bit (PIRl <4>) is set.
Fig. Q.14.1 USART transmitter block diagram
• This interrupt can be enabled or disabled by setting or clearing the
• The TXCKP bit (BAUDCON<4>) allows the TX signal to be
interrupt enable bit, TXIE (PIE1<4>).
inverted (polarity reversed). Devices that buffer signals from TTL
• When TSR fetches the data fromTXREG, it clears the TMR.T flag
to RS-232 levels also invert the signal. Inverting the polarity of the
bit indicatin'g it is full. TSR is parallel in serial out shift register .
TX pin data by setting the TXCKP bit allows for use of circuits
and not· accessible to the programmer. Only write to TXREG
that provide buffering without inverting the signal.
automatically load the TSR.
�.
To set up an asynchronous reception :
CREN.
1. Initialize the SPBRGH : SPBRG registers for the appropriate
11.If using interrupts, ensure that the GIE and PEIE bits in the
,
·
baud rate. Set or clear the BRGH and BRG16 bits, as required,
INTCON register (INTCON<7.:6>) are set.
to achieve the desired baud rate.
I
I
2. Enable the asynchronous serial port by clearing bit, SYNC and
setting bit, SPEN.
Q.16 Write an embedded C program to interface serial port with
PC for both side communication and· displaying . key pressed on
LCD and hyper tenntnal
3. If the signal at the RX pin is to be inverted, set the RXDTP bit.
Ans. : Serial Communication Program
4. If interrupts are desired, set enable bit, RCIE.
/*Baud Rate GENERATION
5. If 9-bit reception is desired, set bit, RX9.
"- n => required baudrate.
6. Enable the reception by setting bit, CREN. * BRGH . = 0
* SPBRG (Fosc I (64 * n)) -1
7. Flag bit, RCIF, will be set when reception is complete and an =
9. Read the 8-bit received data by reading the RCREG register. · #define Fosc 48000000UL
void InitUART(unsi�ned int baudrate);
' �
void main(void)
}
void putch(unsigned char data)
{
InitUART(9600);
{
SendChar(data);
printf("\r\nHello, Enter any Key from Keyboard\r\n");
Init_LCD(); }
unsigned char GetChar(void)
lcdcmd('Jx80):
MSdelay(50);
}
while(l)
Q.17 State featUl·es of RTC and draw an interfacing diagram to
{
interface with PIC.
printf("%c",GetChar()); //Receive character from PC and echo back
Q' [SPPU: May-22, Marks 9, May-18,17, Dec.-17,18, Nov.-16]
lcddata(RCREG);
Ans. : Real Time Clock (RTC) Interface with 12C
· MSdelay(50);
} Real time clock is used to synchronize all the operations of CPU and
} avoid the malfunction in real time considerations.
TXSTA = Ob00100000; /IAsynchronous 8-bit; Transmit • Address and data are fransferrerl serially through an I2C™,
//enabled; Low speed
bidirectional bus.
11 baudrate select ·
•
• Programmable square-wave output signal (1,4,8,64 kHz outpµt) VCC is greater than VBAT +0.2 V and recognizes inputs when
• Signal automatic power-fail detect and $witch circuitry VCC '.,-s greater than 1.25 � VBAT.
• Consumes less than 500 nA in battery - backup Mode �th .
• The c-0mple!,e interface diagram is shown in Fig. Q.17 .1
oscillator running
• Optional industrial temperature range : - 40 °C to + 85 °C Q.18 Draw an lntedaclng diagram of RTC with PIC ? Write an
------:;--
current battery-backup mode.
- ----�1 #include "LCD_SIT.h"
#include "I2C_SIT.h"
!
void set_time(unsigned char address, unsigned char x);
::;:1r-
� 7 �'
�i unsigned char get_time(unsigned char address);
void decode(unsigned char val);
I
void init_data(void);
··�,.. .. . .. .
, , , . ·· ··-·--··--···�-· ·---=··--··· ····--···j
Fig. Q.17.1 RTC Interface to PIC18FXXXX.
Unsigned char sec,min,hrs,date,month, year,Unit, ten;
i2c_interface_init();
SSPADD = 126; //set i2c clock
EEPROM using SPI protocol with PIC 18FXXXX . • EEPROM (electrically erasable programmable read�y memory)
... (SPPU : May•22, Mairlta t) --� . is user-modifiable read-only memory (ROM) that:CU. be msscd
.· ·
.
Ans. : EEPROM Interface with 12C and SPI and reprogr;unmed (written to} repeatedly through· the application
of higher than normal electrical voltage.
• The AT24C02N04A provides 2048/4096 bits of serial electrically
erasable and programmable read-only memory (EEPROM) • It is a type of non-volatile memory used in computers and other
organized as 256/512 words of 8 bits each. electronic devices to store small amounts of data ·that must be
saved when power is removed, e.g., calibration tables or device
Features
configuration.
• Write protect pin for hardware data protection: utilizes different
arrayprotection compared to the AT24C02N04A • With an SPI connection there is always one master dtvice (usually
a microcontroller) which controls the peripheral devices. Typically
• Medium-voltage and standard-voltage operation ;
there are three lines common to all the devices, •
5.0 (VCC = 4.5 V to 5.5 V) and 2.7 (VCC = 2.7 V to 5.5 V)
• Internally organized 256 x 8 (2 K), 512 x 8 (4 K) o Master In Slave Out (MISO) - The Slave line for sending data
to the master,
• Two-wire serial interface.
o Master Out Slave In (MOS!) - The Master line f0r Sending data
• Schmitt trigger, filtered inputs for noise suppression.
to the peripherals,
• Bidirectional data transfer protocol.
• 400 kHz (2.7 V, 5 V) Clock rate. o Serial Clock (SCK) - the clock pulses which synchronize data
transmission generated by the master and
• 8-byte Page (2 K), 16-byte Page (4 K) write modes. .
,
• Partial page writes allowed. o Slave Select pin - the pin on each device that the master can use
to enable and disable specific devices. When a device's Slave
• Self-timed write cycle (5 ms Max).
• High reliability. j
;
Select pin is low, it communicates with the master. When it's
high, it ignores the e
mast r.
Endurance : One million write cycles.
t
• .-i
o The SPI Controller here acts as a master device and controls
• Data Retention : 100 Years.
EEPROM which acts. as a slave. The read-write operations are
0lr
·
VDD
/*SP!_ CO.MMANDS* I
'•
u
C64 #define READ Ox03
:li
� r:...-....,
VOD
#define WRITE Ox02
#define WRDI Ox04
Tl
#define WREN Ox06
'
#define RD$R Ox05
R49 . R50
4.7 K ·7 K #define WRSR OxOl
v 1 ( pF
c�l2 . 13
unsigned char i,a,j;
1
C22 pF r==i ·10
Y18 unsigned char Msg[) ="SP! TEST Program";
... ....;;;:;;;;;;�;;;;;;;;;;;;;;;;;;;;:;
....""" ;; ;;;;
;;;; ;; ;;
;;; ;;;; ;;; ;;;;
; ;; ; ;;
;;; ;;;; ;;; ;;;;
; ;; ;;; ;; ;;; ;;
; ;; ;;; ;;
;;; ;;
;;; ;;
;;; ;; ;;; ;;
;; ;; ;;; ;;;;;;;
;;; ;
�· A Guide for E11gi11eerillg St11de11ts-.
� A G11idefor E11gi11eeri11g S111de11ts
1t1:
!:
H
Microcontrol/er
unsigned char x;
7 - 43 Serial Port Programming am,' Interfacing witl1 PICI BFX
XXX Microcontroller -
7 44 Serial Pol'( Programming and InterfacllllJ wit// PICIBFXXXX
,•1 · ;:
SCK=l;
TRISD=O; //and set the remaining pins 12.s output
Data=Data<<l;
( Serial_init();//Setup the serial port
. SPi_init();
SCK=O;
!
·}
· DelayMs(lO);
for(i=O; i<S; i++) //wait for.OxOO--device net busy
'1.
while(ISPi_RDSR()); //SPI ready?
J {
\.
··.·l · i
SPi_WRITE(OxOO); //Send initialisation Command
· SCK=l:
�·I DelayMs(lO);
.
Data I =((SO & 1)?1:0);
:!I
:.,
while(l)
�;. ·, ·
.Data=Data<<l;
. {o
SCK=O;
.
x=O;
� while(x< 16)
}
·
CS=l; · //Pull up
ill; {
return !Data;
TXREG=PORTD=SPi_READ(x); //Rea
d byte frorr. 25c040 and
}
send
II via Usart
void SPi_WRITE(unsigned char Addr)
++x;
DelayMs(50); {
unsigned char Data=WREN;
}
int AH=WRITE;
}
AH=(AH<<B)+Addr;
}
CS=O;
for(i=Q;i<S;i++) //Send Write Enable
void SPi_init()
{ {
CS=l; SI=(Data & Ox80)?1:0;
//Make CS pin high
SI=O; SCK=l;
//Clear input pin
Data=Data<<l;
SCK=O; //Clock low
SCK=O;
}
unsigned char SPi_RDSR() }
//Ri.se CS and pull down again
0
{ CS=l;
SCK=O; }
} CS=1;
{or(i=O;i<16;i++) //Send Data's return RData;
{ }
· Data=Msg[i]; void Serial_init()
for(j=O;j<S;j++) {
{ TXSTA=Ox24; //Transmit Enable
SI=(Data & Ox80)?1:0; SPBRG=BAUD_VAL; //9600 baud atlOMhz
SCK=1; RCSTA=Ox90; //Usart Enable, Continuous receive enable
Data=Data<<1; TXREG=OxOO; //Dummy transmission
'
SCK=O; printf("\033[2J"); //Clear the Hyphartermina!;
} }
} void putch(unsigned char character)
CS=l; {
} while(ITXIF); //Wait for the TXREG register to be empty
unsigned char SPi_READ(unsigned char Addr) TXREG=character; //Display the Character
{ }
int Data=READ;
unsigned char RData=O;
'
'' . :.,
frequency of oscillator ranging from 0 to 20 :MHz and requires power 600 - rnA at voltages from 4.5 V to 36 V. It is designed to drive
supp:y of± 5 or ±12V. A simple circuit design for +5 Vis shown in inductive lQads such as relays, solenoids, de and· pipolar stepping
·motors, �, well· as other high-current/high-voltage loads in·
positive-
Fig. Q.21.1_
ed
..
�
"
"" """" ;{1
""······;c.1· . ... supply· applications. Wheri.. an enable input is high, the associat
their
J1
;;;;->
- ,dfiyers are enabled and their outputs are active and in phase with
�
.
.
"inputs.
��·
� �·'
·
\:li ...l. ...l.::11
, i;�;���,���ff�;li�....�on
C1(•
,;l':.�·� " ''
T.��.:.·.:.···l--�.:.:.�.. . ..T
•J. 1 .•1·
."!"�'�
dewn.
i'
J
Step 4 : Configuration of Port :
.
r
#include<stdio.h>.
void MSdelay(unsigned int itime);
. · -� ••
void main()
{
. 0
TRISD=OxOO;
••• �
TRISB=OxOO;
" while(l)
{
LATD=Ox56;
s
I MSdelay(3000);
LATD=Ox59;
--�lJ·
'
· MSdelay(3000);
LATD:::Ox65;
--r �
..
...
�
LATB=OxOl;
...
"
MSdelay( 1000);
LATB=OxOO;
MSdelay(3000);
LATB==Ox02;
MSdelay(1000);
T�ATB=OxOO;
LATD=Ox95;
xJ LATB=OxOB;
MSdelay(lOOO);
<:=� LATB=OxOO;
� MSdelay(3000);
LATB=Ox04;
MSdelay(lOOO);
LATB=OxOO;
w
}
}
void MSdelay(unsigned int itime)
Fig. Q.21.2 : Traffic light controller system
{
I unsigned inti,j;
i for(i=O;i<itime;i+ +)
�
' ".'."""� A Guide for Eugh12�rillg St11de11ts
0 I
!
� A Guide/or E11gi11eeri11g Students
,I
\!'\
1!1
I''
Microco11troller · 7 51 - Serlul Port Progroh1ming a11d Intelfacing wit/1 PICJBF)(}()()(
(. ....... .. . . . .. ............ .... ... ................ inPert1.ili'P.ofilt5. io. ei11'&1Tit>&r............................................. .. .... . . .�\ Serial Port Programming and Inteefudng wl(/1 PICJ BFXXXX
Mlcrocontroller 7 52-
I: T R -
,
. .
. 0\
11
.. . .
1:t r 2. MSSP Status Register (SSPSTAT)- Used for SPI and I2C modes\
/· .
.: j
with checking of edge for clocking and check for. transfer of \
1. Serial communication is cost effective than parallel.
! .
1 bit 7
6. ·Data on I2C bus is communicated between START, STOP
I 3, MSS,P Control Register2 (SSPCON2)
.
I r-5c:�
-
--+---�b--:"'
·
Iil_Jtt. j
�b. ; ! i It -0-�!
·
7 ,_ ...
: . .
! .
10. Flash bits in PIR 1 register are used to indicate the data
'
1 1 �� �RMT=:i���
.
-
J ._;.�-----��!.g_ .
i SFRS USED:
-·----- _______
.
..
·: It is 8 bit
I
Read and write, used to i register, used to enable the serial portto receive data.
--;;-�
-
I
i
select the oscillator frequency, enable operation, and check for low i .
and high level of clock.
I
.
. 11 ��: � R/W-0 R/W-0 R/W-0 R-0" R-1
j
: 11 ! SPEN RX9 SREN CREN ADDEN FERR OERR RX9D
.
. . . . . .. .
. . . . . . . .
r.......... .... . ....... ......... .. .......... ... . ........ .. ................... . .. ....................... ........... ... ..... .. .... . . ............ ..... ... - .......................-............. � .
... . !
� _J
i i'M'M•--owo�ow"''�'�""''_H,0--WOWN.WoM•---o'
NM-.W�Mo�""'-�""''M"'"°-ONNl.WM-"'w·"- . .
-WM"""'""'-'°'•!
!: bit 7 bit 0
iL .
.
.. ............... . ...... ..... �.,,,, ... ... ................. . . i
..1 l
END ... �
.
.... . -....-..........._..,....._.,,..,_.,_"'"""""'-· . ...... .
. . ..
. .
�--�--�---...·��- .
. .
. . . .
. . . .
\ ...............
. ..
,,,...,,,,,, ...,,...,,,,,,,,.,._,...,,,.._...,._......._.,V...
... ,,,_...., _........,
...., ....,.,�,,A'........,,, ... .,_...._.,
.... ........,_.,..,,.,.,,.,_ ,,.,,........._,__....,.., .......,,,,.,,...,...,,,..,.,,....,....,, ,_,... .......,...,t'// '·
.liiuh/e/�;i�ilheering Studellts
-� · ·.
Microcontroller S-2 Solvef! University Question Paper
I
Q.3 A) Enlist specifications of ADC used, also draw the
[MAv-2022-<E-Nn sEM> �ss;o1-1�64-llr-so1��<1 -Pape-; J · interfacing diagram of temperature sensor with PIC
i) Attempt Q.J or Q.2, Q.3 or Q.4, Q.5 or Q.6, Q.7 or Q.8. (Refer Q.10 of Chapter - 5) [8]
ii) Neat diagrams must be drawn wherever necessary. OR
ii) Figures to the right side indicate full marks.
Q.4 A) Draw and explain the Timer 1 operation of PIC l8Fxxxx
iv) Assume suitable data, if necessary.
in details, compare the Timer 0, 1 and 2.
Q.1 A) Explain in depth the programming model of PIC 18Fxxxx (Refer Q.5 of Chapter - 5) [9]
microcontroller. (Refer Q.8 of Chapter 4) [6]
Write a program for 1 kHz and 10 % duty cycle PWM
-
B)
B) Explain the power down modes of PIC 18Fxxxx. generation _with Fosc = JO .MHz.
(Refer Q.3 of Chapter - 4) [6] (Refer Q.21 of Chapter • 5) [8]
C) Enlistfeatures of PJC 18Fxxx microcontroller. Q.5 A) Write an embedded C program to blink LED connected to
(Refer Q.3 of Chapter - 4) [6] port B of P/Cl8Fxxxx with ·delay of 1 msec using Timer
OR 0, 16 bit. [9)
Ans. : Refer Q.6 of Chapter - 4 for interfacing and program,
Q.2 A) Draw ·and explain the reset functiqnal diagram of PIC
Refer Q.7 of Chapter - ·5 - For generation of Delay
J8Fxxxx. (Refer Q.11 of Chapter - 4) [6]
Calculation of TMROH and TMROL values
B) Explain with example functioning of ALU in PIC
1 . Assume that Crystal frequency = 1 0 MHz
J 8Fxxxx. (Refer Q.4 of Chapter - 4) [6]
2. Internal time delay = 4/( 1 0 x 106) = 0.4 µs
. CJ Draw and explain the program memory of PIC 18Fxxxx.
3. N = 1 ms/0.4 µs = 2500
(Refer Q.7 of Chapter - 4) [6]
4. Count = 65536 - 2500 = (63036)10
#include <Ptsncxxx.h.> OR
. : ..: . .'·i
void TODelay(void); :
Q.6 A) Draw and explain port structure of PIC 18Fxxxx
·
void main(void)
·:··
.
:i
} of Chaptf!r - 6) [9]
} Q.7 A) Expfain with block c,'iagram I2C mode of MSSP structure
void TODelay [)
in detail. (Refer Q.9 of Chapter - 7) [9]
{
TOCON=Ox08; 11 TimerO, 16 bit, no prescaler . B) State features of RTC and draw an interfacing diagram
TMROH=OxF6; 11 Load Hig�er byte in TMROH with PIC' 18Fxxxx. · (Refer Q.17 of Chapter - 7) [8]
TMROL= Ox3C; 11 Load Lower byte to TMROL ' OR
TOCONbits.TMROON=1; 11 Start the timer for upcount
Q.8 A) Explain the use of BRG register for calculation for baud
while(INTCONbits.TMROIF==0); 11 Check for overflow
rate with UART receiver block diagram.
TOCONbits.TMROON=O; 11 Tum off timer
(Refer Q.ll(Calculation of BRGH) and Q.15 (USART
·
BJ Design a PIC 18Fxxxx test board with facility of status B) Draw an interfacing diagram· of EEPROM with
indication on· LED, Buzzer and lamp connected PIC 18Fxxxx using SP! protocol with initialization
PIC l8Fxxxx through relay, write embedded C program program. (Refer Q.19 of Chapter - 7) [8]
,.
;;
(Refer Q.13 of Chapter - 6) [9]
END... 25
.' i