0% found this document useful (0 votes)
58 views107 pages

Chap 5

Embedded systems

Uploaded by

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

Chap 5

Embedded systems

Uploaded by

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

Embedded Systems (ECEg-5702)

PIC Microcontroller

23/04/2023 1
Outline of the Lecture

Introduction

PIC16F877A Architecture:
• The power supply
• The reset
• The clock sources
• Watchdog timers
• The configuration registers
• Ports
• Interrupts
• Timers
• Capture/Compare/PWM modules (CCP)
• Analog-to-Digital Converter (A/D) Module
• Serial Communication
• Program memory organization
• Data memory organization

Interfacing

23/04/2023 2
Microcontrollers
• There are hundreds of microcontroller manufactures, but here are the top
vendors in the global microcontroller market:

Company Website Families


Microchip Technology microchip.com PIC Series

Texas Instruments(TI) Inc. ti.com MSP430 Series

Cypress Semiconductor http://www.cypress.com PSoC Series

NXP Semiconductor https://www.nxp.com/ i.MX Series

Infineon Technologies https://www.infineon.com C16x, C500

STMicoelectronics http://www.st.com ST or STM Series

Silicon Labs https://www.silabs.com C8051F

Atmel Corporation atmel.com AVR Series

23/04/2023 3
Microcontrollers
Atmel’s AVR series
✔ Atmel has broad portfolio of devices: Starting from small 8-bit flash µCs to advanced
cores that run operating systems, like Linux and windows CE .
✔ Atmega (Atmega8, Atmega16….)
▪ 8-bit flash based µCs
▪ up to 16MIPS, 8-512KB flash…costs $6 max.
▪ In-circuit programmable…programmer HW not required
▪ free GCC based compiler and assembler STK-500K programmer and debugger kit available.

Texas Instruments’ MSP Series


• Series world’s lowest power µCs
• TI has broad portfolio of devices: Starting from small 16-bit flash µCs to advanced SOCs
that run operating systems, like Linux and windows CE
• MSP430xxx
✔ 16-bit ultra low power flash based µCs
✔ up to 25MIPS, 4-120KB RAM…costs $5 max.
✔ on-chip LCD controller, up to 16-bit fast ADC

In This tutorial, We will focus on Microchip’s PICs Microcontroller.

23/04/2023 4
PIC Microcontroller Series
• Widely used device from Microchip Technology
 Sold > 10 billion PIC controllers
 Several device families
✔ Many devices per family
✔ Common development environment
 Widely available
✔ Large user base
✔ Extensive application notes
 Low cost
 Free / low cost development tools
• Basic architectural features
 Pipelined RISC microprocessor core
 Accumulator execution model
 Data width — 8 / 16 / 32 bits
 Instruction width — 12 / 14 / 16 / 32 bits
• Microchip PIC series: there are three families:
I. Baseline (PIC10Cxxx…….PIC12Cxxx)
✔ Highly limited ROM based 8-bit µCs
II. Mid range (PIC16Fxxx)
✔ 8-bit flash based µCs
✔ PIC16F8xx up to 5MIPS, 8KB flash…costs $3 max.
✔ In-circuit programmable…programmer HW not required
III. High end (PIC18Fxxx, dsPIC, PIC24xxx and PIC32MX..)
✔ 8, 16 and 32-bit architecture
✔ on chip USB, Ethernet, GPS, …

23/04/2023 5
PIC architecture is a “Harvard” Architecture

Feature of Harvard architecture


• Near all instructions are single instruction word
• Only one fetch per instruction
• Instruction fetch and execute are pipelined so you can operate at near
clock rate instructions per second
• 2 separate buses
• One for instructions and one for data

9/20/6 6
MICROCHIP Microcontroller Family

• Data width
✔ 8 / 16/ 32 bits
✔ Wider integer ⇒ higher precision arithmetic
• Instruction width
✔ 12 / 14 / 16 / 32 bits
✔ Wider instruction ⇒ more complex instructions + higher precision arithmetic

23/04/2023 7
Learning PIC Architecture
Some general observations
• Variety
✔ Hundreds of PIC devices in 3 families and several sub-families
• Updates
✔ Microchip Technology upgrades devices frequently
✔ Familiar devices replaced with new model
• Instruction Set Architecture
✔ 8 and 16 bit devices share approximately uniform instruction set
✔ PIC32 implements MIPS ISA
• Limitations
✔ Course takes general pedagogical approach to PIC as typical MCU
✔ Focus on 8-bit devices — Mid-Range + PIC16
✔ Many books + websites on PIC with general-sounding titles
✔ Each device is unique

23/04/2023 8
23/04/2023 9
Some Typical 8‐bit PIC Device Families

23/04/2023 10
PIC16F87xA families

23/04/2023 11
23/04/2023 12
Introduction to PIC16F877A
• PIC16F877A is an 8 bit microcontroller developed by Microchip.
• The PIC microcontroller PIC16f877a is one of the most renowned
microcontrollers in the industry.
• This controller is very convenient to use, the coding or programming of this
controller is also easier.
• One of the main advantages is that it can be write-erase as many times as
possible because it use FLASH memory technology.
• It has a total number of 40 pins and there are 33 pins for input and output.

23/04/2023 13
Basic features of PIC16F877A
• RISC architecture • 256 bytes EEPROM memory
✔ 35 single world instructions to learn • 368 bytes RAM memory
✔ All single-cycle instructions except • A/D converter:
branches ✔ 10-bit resolution, 8-channel A/D Converter
• Operating frequency 0-20 MHz • 3 independent timers/counters
• Precision internal oscillator • Watch-dog timer with its own on-chip
RC oscillator for reliable operation
✔ Factory calibrated
✔ Software selectable frequency range of • Analogue comparator module with
4MHz to 31KHz ✔ Two analogue comparators
✔ Fixed voltage reference (0.6V)
• Power supply voltage 2.0-5.5V ✔ Programmable on-chip voltage reference
• Power-Saving Sleep Mode • Two Capture, Compare, PWM module
• Brown-out Reset (BOR) with • USART module with 9 bit address
detection
software control option
• Synchronous Serial Port (SSP) with
• 33 I/O pins, 5 I/O ports master mode and master/slave.
• 8K ROM memory in FLASH ✔ supports SPI and I2C mode
program memory technology

23/04/2023 14
PIC16F877A Pin Configuration
• The pin configuration of the PIC16F877A microcontroller (DIP package) is
shown below

23/04/2023 15
PIC16F877A Architecture

23/04/2023 16
40 Pins of PIC16F877A
• 33 I/O pins, 5 I/O ports
✔ The pins RA0-RA5, RB0-RB7, RC0-RC7, and RD0-RD7 are digital I/O pins.
✔ The pins AN0-AN7 are for analog I/O
✔ Pin TX and RX which share locations with RC6 and RC7, are used for serial communication
✔ The pins CCP1 and CCP2, which share locations with RC1 and RC2, can be used for a PWM signal

• The remaining pins deal with power/ground, the clock signal, and programmer I/O.
• 5 Power Pins
✔ Power to Pin 1 (Vpp) – connected via 47k Resistor
✔ Power to Pin 11 (Vdd)
✔ Ground to Pin 12 (Vss)
✔ Power to Pin 32 (Vdd)
✔ Ground to Pin 31 (Vss)
• 2 External Clock Pins
✔ Crystal Oscillator to Pins 13 & 14 (OSC1, OSC2), the polarity doesn’t matter.
✔ Capacitor into power & ground

23/04/2023 17
Reset
• The reset is used for putting the microcontroller into a known condition in
cases when the microcontroller behave inaccurate under certain
undesirable conditions.
• Resetting a PIC16F microcontroller starts execution of the program from
address 0000H of the program memory.
• The PIC16F87XA series have various kinds of Reset:
✔ Power-on Reset (POR)
✔ MCLR Reset during normal operation
✔ MCLR Reset during Sleep
✔ WDT Reset (during normal operation)
✔ WDT Wake-up (during Sleep)
✔ Brown-out Reset (BOR)
• Two types of resets are commonly used: power-on reset and external reset
using the MCLR pin.

23/04/2023 18
Power-on Reset (POR)
• All PIC microcontroller devices have a built-in Power-On Reset circuit.
• A power-on rest(PoR) generator is a microcontroller peripheral that
generates a rest signal when power is applied.
• It ensures that the device starts operating in a known state. it will be reset and
start operation in a properly initialized way.
Power-up Timer (PWRT)
✔ The Power-up Timer provides a fixed 72 ms nominal time-out on
power-up only from the POR.
✔ The chip is kept in Reset as long as the PWRT is active.
✔ The PWRT’s time delay allows VDD to rise to an acceptable level.
✔ A configuration bit is provided to enable or disable the PWRT.

23/04/2023 19
Reset pin: MCLR
• Reset pin is usually marked as MCLR (Master Clear Reset).
• Pin1 is the master clear pin of PIC16F877A.
• It is used for external reset of the microcontroller by applying a logic zero (0) or
one (1) to it, which depends on the type of the microcontroller.
• PIC16F877A has an active low MCLR, meaning that it should constantly be
given a voltage of 5V and if 0 V are given then the controller is reset.
• Resetting the controller will bring it back to the first line of the program that has
been burned into the IC.
• When we want to reset the IC we just have to
push the button which will bring the MCLR pin
to 0 potential thereby resetting the controller.

23/04/2023 20
Watchdog Timer
• A watchdog timer is a timer connected to a completely separate RC oscillator
within the microcontroller.
• If the watchdog timer is enabled, every time it counts up to the maximum value,
the microcontroller reset occurs and the program execution starts from the first
instruction.
• All PIC microcontroller devices have a Watchdog timer which gives the code
developer a way to reset the device in the event of unexpected code operation.
• The WDT can be permanently disabled by clearing configuration bit, WDTE.

23/04/2023 21
Brown-out Reset (BOR):Rest at the supply voltage drop below the
permissible

• PIC microcontroller devices have a built-in Brown-Out Reset (BOR) feature that resets the
device when the supply voltage drops too low.
• This is used to insure that the device will not try to run at a voltage that is too low for correct
operation.
• The configuration bit, BODEN, can enable or disable the Brown-out Reset circuit.
• If VDD falls below VBOR (about 4V) for longer than TBOR (about 100 µS), the brown-out
situation will reset the device. If VDD falls below VBOR for less than TBOR, a Reset may not
occur.
• Once the brown-out occurs, the device will remain in Brown-out Reset until VDD rises above
VBOR.

23/04/2023 22
Clock Sources
• The PIC16F87XA can be operated in four different oscillator
modes.
✔ LP Low-Power Crystal
✔ XT Crystal/Resonator
✔ HS High-Speed Crystal/Resonator
✔ RC Resistor/Capacitor
OSC OSC
• The user can program two configuration bits (F 1 and F 0) to
select one of these four modes:
• FOSC1:FOSC0: Oscillator Selection bits
11 = RC oscillator
10 = HS oscillator
01 = XT oscillator
00 = LP oscillator

23/04/2023 23
Clock Sources
• Crystal Oscillators or Ceramic Resonators :
✔ In XT, LP or HS modes, a crystal or ceramic resonator is connected to the
OSC1/CLKI and OSC2/CLKO pins to establish oscillation.
✔ For applications where accuracy of timing is important, a crystal should be used.
✔ If a crystal is used, a parallel resonant crystal must be chosen, since series
resonant crystals do not oscillate when the system is first powered.
✔ Figure below shows how a crystal is connected to the microcontroller. The
capacitor values depend on the mode of the crystal and the selected frequency.
✔ Higher capacitance increases the oscillator stability but also increases the
start-up time.

23/04/2023 24
Clock Sources
• RC OSCILLATOR :
✔ For timing insensitive applications, the “RC” device option offers additional cost
savings.
✔ The RC oscillator frequency is a function of the supply voltage, the
resistor (REXT) and capacitor (CEXT) values and the operating temperature.
✔ A close approximation of the clock frequency is 1/(4.2RC),
✔ The oscillator frequency divided by 4 (FOSC/4) is available on pin OSC2 of the
microcontroller.

23/04/2023 25
Ports
• Port is a group of pins in microcontroller which can be accessed simultaneously.
• Physically, port is a register inside a microcontroller which is connected by wires to the
pins of a microcontroller.
• When working with a port we may want to:
✔ Set port direction
✔ Set an output value
✔ Read an input value
✔ Set an output value and then read back the output value
• There are 5 ports in PIC16F877A that provide parallel I/O Interfaces to outside world
PORTA, PORTB, PORTC, PORTD, PORTE.
✔ one 6-bit ports: A ,
✔ three 8-bit ports: B ,C,D and
✔ one 3 bit port: E
• I/O line can either be INPUT or OUTPUT.
• By clearing some bit of the TRISx register, the corresponding port pin is configured as
input or output.
• If some bit of the TRISx register (bit=1), the corresponding port pin is configured as
input.
• If some bit of the TRISx register (bit=0), the corresponding port pin is configured as
output.

23/04/2023 26
I/O pin
The pin can be set for input or output data transfer

Write TRIS bit Data


Direction Tri-state
Latch Output
Enable

Output Output
CPU Data Bus
Data Current
Latch Driver
Write data bit

Input
Data
Read data bit Latch

Analogue input
multiplexer

23/04/2023 27
PORTA and TRISA
• PORTA is a 6-bit wide, bidirectional port located from Pin 2 to 7
• All of the Port A pins except RA4 have a shared use with the analog multiplexer
(MUX).
• The first step in configuring Port A is to select which pins are to be set as digital
input/output and which are to be analog inputs.
• This is done with the lower four bits of the ADCON1 register file.
• If we want all of Port A to be digital, the setting is 0x06.
• The corresponding data direction register is TRISA.
• Setting a TRISA bit ( = 1) will make the corresponding PORTA pin an input
• Clearing a TRISA bit (= 0) will make the corresponding PORTA pin an output.

23/04/2023 28
ADCON1 "Analog vs Digital" Selection Codes

• if we want all of the Port A bits as “digital”, ADCON1 must set to 0x06

23/04/2023 29
PORTB and TRISB
• PORTB is a 8-bit wide, bidirectional port located from Pin 33 to 40
• The corresponding data direction register is TRISB.
• Setting a TRISB bit ( = 1) will make the corresponding PORTB pin an
input
• Clearing a TRISB bit (= 0) will make the corresponding PORTB pin an
output.
• Three pins of PORTB are multiplexed with the In-Circuit Debugger and
Low-Voltage Programming function:RB3/PGM,RB6/PGC and RB7/PGD

23/04/2023 30
PORTC and TRISC
• PORTC is 8-bit wide, bidirectional port located from Pin 15 to 18 and pin 23
to 26
• The corresponding data direction register is TRISC.
• Setting a TRISC bit ( = 1) will make the corresponding PORTC pin an input
• Clearing a TRISC bit (= 0) will make the corresponding PORTC pin an
output.
• PORTC is multiplexed with several peripheral functions. PORTC pins have
Schmitt Trigger input buffers.
• When the I2C module is enabled, the PORTC<4:3>pins can be configured
with normal I2C levels, or with SMBus levels, by using the CKE bit
(SSPSTAT<6>).
• When enabling peripheral functions, care should be taken in defining TRIS
bits for each PORTC pin.
• Some peripherals override the TRIS bit to make a pin an output, while other
peripherals override the TRIS bit to make a pin an input.

23/04/2023 31
PORTD and TRISD
• PORTD is a 8-bit wide, bidirectional port located from Pin 33 to 40
• The corresponding data direction register is TRISD.
• Setting a TRISD bit ( = 1) will make the corresponding PORTD pin an
input
• Clearing a TRISD bit (= 0) will make the corresponding PORTD pin an
output.
• PORTD is an 8-bit port with Schmitt Trigger input buffers.
• PORTD can be configured as an 8-bit wide microprocessor port (Parallel
Slave Port) by setting control bit, PSPMODE (TRISE<4>).

23/04/2023 32
PORTE and TRISE
• PORTE is a 3-bit wide, bidirectional port located from Pin 8 to 10
(RE0/RD/AN5, RE1/WR/AN6 and RE2/CS/AN7)
• The Port E pins also share their pins with the analog multiplexer as in Port
A and its use is identical with Port A.
• The corresponding data direction register is TRISE.
• Setting a TRISE bit ( = 1) will make the corresponding PORTE pin an
input
• Clearing a TRISE bit (= 0) will make the corresponding PORTE pin an
output.

23/04/2023 33
TRISybits.TRISyx and PORTybits.Ryx
• TRISybits.TRISyx is used to configure the direction of single pin x in a
PORT y.
• PORTybits.Ryx is used to access(read or write) data from single pin x in
PORT y.
• Example: if we want to set the direction of PORTA pin 2 as an input, we
will set TRISAbits.TRISA2 to 1 and we use PORTAbits.RA2 to read the
state of the pin.

23/04/2023 34
Blink LED Schematic Diagram

23/04/2023 35
Blink LED
• Hardware Setup void initalization()
✔ Connect a pull-up resister R2 on MCLR pin {
TRISC = 0x00;//configuring PORTC as
(Pin1) of the controller, the other end of which
output
will be tied to Vdd.
}
✔ For oscillation, connect a 4MHz crystal across void delay_ms(int ms)
pin13 and pin14 of the microcontroller with 2 {
capacitors C1 and C2 on either side of the int i;
crystal. for(i=0;i<ms;i++);
✔ The LED is connected to Pin RC1 of PortC via }
a 470R resister R1. int main(int argc, char** argv) {
initalization();
//Loop executed infinite times
while(1)
{
//Pin1 of PORTC high
PORTC=0x02;//0b00000010;
delay_ms(10000); //Delay of 1 sec
// BEGIN CONFIG
#pragma config FOSC = HS; // Oscillator Selection bits (HS oscillator)
//Pin1 of PORTC low
#pragma config WDTE = ON; // Watchdog Timer Enable bit (WDT enabled)
PORTC=0b00000000;
#pragma config PWRTE = ON ; // Power-up Timer Enable bit (PWRT
delay_ms(10000);//Delay of 1 sec
disabled)
}
#pragma config BOREN =ON; // Brown-out Reset Enable bit (BOR enabled)
return 0;
//END CONFIG
}

23/04/2023 36
Blink LED Using Push Button

23/04/2023 37
Blink LED With Push Button
int main(int argc, char** argv) {
#include<xc.h> initalization();
void initalization() int i=0;
{ //Loop executed infinite times
while(1)
{
TRISC = 0x00;//configuring PORTC as output while((PORTB &(0b00000010)) == 0b00000010)
TRISB = 0xFF;//configuring PORTB as input {
if(i==0)
} {
//Pin1 of PORTC high
PORTC= 0x02;//0b00000010;
void delay_ms(int ms) delay_ms(10000); //Delay of 1 sec
{ i++;
int i; }
for(i=0;i<ms;i++); else
} {
PORTC= 0x00;//0b00000010;
delay_ms(10000); //Delay of 1 sec
i--;
}
}
}
return 0;
}

23/04/2023 38
Exercise
• Design DC Motor direction control system using PIC16F877A. The system
has three push buttons, two of them used for rotating the motor CW and
CCW. The third push button used to stop the rotating motor. Please use
L293D motor driver IC to interface the motor with the microcontroller.
✔ Draw the block diagram
✔ Draw the schematic diagram on Proteus
✔ Write the firmware code.

23/04/2023 39
How does the processor of the microcontroller get the required information
from the external I/O and peripherals devices ?

• There are two ways for the processor to get information from the external
devices:
✔ using polling
✔ using interrupts
• Polling:
✔ The microcontroller accesses the external device at the exact time interval , and gets
the required information.
✔ The programmer is the one who determines the time intervals in which microcontroller
contacts the device.
✔ In the Polling method, the PIC microcontroller must "access by itself" the device and
ask for the information it needs for processing.
✔ The main drawback of using polling method for writing a program is
▪ It waste the time of microcontroller, which needs to wait and check whether the new information has
arrived.
▪ not suitable for time critical or real time system

23/04/2023 40
Interrupts
• Interrupt is one of the most powerful feature in embedded applications.
• Almost all the real time applications are implemented using Interrupts.
• Interrupts are special events that requires immediate attention, it stops a
microcontroller/microprocessor from the running task and to serve a special task known as
Interrupt Service Routine (ISR) or Interrupt Handler.
• Interrupts will always be active listening for some particular actions to happen and when
they occur they execute a piece of code and then gets back to the normal function. This
piece of code is called the interrupt service routine (ISR).
• Interrupts can be useful in many applications such as:
✔ Time critical applications.
▪ For example, in an emergency such as a power failure or fire in a plant the CPU may have to
shut down the system immediately in an orderly manner. In such applications an external
interrupt can force the CPU to stop whatever it is doing and take immediate action.
✔ Performing routine tasks.
▪ A timer interrupt scheduled with the required timing can divert the CPU from normal program
execution to accomplish the task at the precise time required action.
✔ Task switching in multi-tasking applications.
▪ In multi-tasking applications, each task may have a finite time to execute its code. Interrupt
mechanisms can be used to stop a task should it consume more than its allocated time.
✔ To service peripheral devices quickly.
▪ Some applications may need to know when a task, such as an A/D conversion, is completed.
This can be accomplished by continuously checking the completion flag of the A/D
converter. A more elegant solution would be to enable the A/D completion interrupt so the
CPU is forced to read the converted data as soon as it becomes available.

23/04/2023 41
Interrupts
• In Microcontrollers there are two main types of interrupts. They are
✔ External Interrupt and
✔ Internal Interrupt.
• The internal Interrupts occur inside the Microntroller for performing a task, for
example Timer Interrupts, ADC Interrupts etc..
✔ These interrupts are triggered by the software to complete the Timer operation or ADC
operation respectively.
• The external interrupt is the one that can get triggered by the user.
✔ for instance an external interrupt can be trigger using a push button .
• PIC Microcontroller consists of both Hardware and Software Interrupts.
• If the interrupts are generated by external hardware at certain pins of
microcontroller, or by inbuilt devices like timer, they are called Hardware
Interrupts.
• While Software Interrupts are generated by a piece of code in the program.
• There are lots of types of interrupts in Microcontroller and the PIC16F87XA family
has up to 15 sources of interrupt.

23/04/2023 42
Interrupts in PIC16F877A
• PIC 16F877A has the following 15 interrupt sources :
✔ External
✔ Timer 0
✔ Timer 1
✔ RB Port Change
✔ Parallel Slave Port Read/Write
✔ A/D Converter
✔ USART Receive
✔ USART Transmit
✔ Synchronous Serial Port
✔ CCP1 (Capture, Compare, PWM)
✔ CCP2 (Capture, Compare, PWM)
✔ TMR2 to PR2 Match
✔ Comparator
✔ EEPROM Write Operation
✔ Bus Collision
• There are 5 registers that used to control the operation of Interrupts in PIC16F877A
Microcontroller :
✔ INTCON Register
✔ PIE1 Register
✔ PIR1 Register
✔ PIE2 Register
✔ PIR2 Register
• PIC16F877A the 33th pin RBO/INT is used for external interrupt.

23/04/2023 43
INTCON Register
• INTCON Register is a readable and writeable register which contains various enable
and flag bits for External and Internal Interrupts.

• GIE: Global Interrupt Enable bit


• TMR0IF: TMR0 Overflow Interrupt Flag bit
✔ 1-Enables all unmasked interrupts
✔ 0-Disables all interrupts ✔ 1-TMR0 register has overflowed (must be
cleared in software)
• PEIE: Peripheral Interrupt Enable bit
✔ 0-TMR0 register did not overflow
• 1-Enables all unmasked peripheral interrupts
• 0-Disables all peripheral interrupts • INTF: B0/INT External Interrupt Flag
• TMR0IE: TMR0 Overflow Interrupt Enable bit ✔ 1 – The RB0/INT external interrupt occurred. It
must be cleared in software.
✔ 1-Enables the TMR0 interrupt
✔ 0-Disables the TMR0 interrupt
✔ 0 – The RB0/INT external interrupt did not
occur
• INTE: RB0/INT External Interrupt Enable
• RBIF: RB Port Change Interrupt Flag
✔ 1 – Enables the RB0/INT external interrupt
✔ 0 – Disables the RB0/INT external interrupt
✔ 1 – At least one of the RB7 – RB4 pins changed
state, a mismatch condition will continue to set
• RBIE: RB Port Change Interrupt Enable the bit. Reading PORTB will end the mismatch
✔ 1 – Enables the RB port change interrupt condition and allow the bit to be cleared. It
✔ 0 – Disables the RB port change interrupt must be cleared in software.
✔ 0 – None of the RB7 – RB4 pins have changed
state

23/04/2023 44
Interrupt
• Interrupts can be easily handled by using reserved word ‘interrupt’. MPLAB and
MikroC PRO for PIC Microcontrollers implicitly declares a function ‘interrupt’
to handle interrupts which cannot be re-declared.

void interrupt() // Interrupt ISR


{

}
• This function is a special function.
• The interrupt functions is called by the hardware itself and operates by the
following steps:
✔ If the interrupt function is loaded into the memory, the function will waits for a moment for
the interrupt to occur;
✔ When the interrupt has occurred, the operating system stops the execution of the main
function and free itself to perform the interrupt function;
✔ After the execution of the interrupt function, the operating system continues to run the main
function from the place it stopped before the interrupt has occurred.

23/04/2023 45
A push button switch is connected to the External Interrupt pin INT of the
External Interrupt Microcontroller. When this button is pressed, the microcontroller is interrupted and
the ISR is executed. The ISR toggles or change the status of PORTC pin 0 .

#include <xc.h> void main(void)


#define _XTAL_FREQ 20000000 {
void interrupt ISR(void) // Initialize external interrupts on RB0 pin
{ InitExternal_INT();
if(INTF==1) //If External Edge INT Interrupt TRISCbits.TRISC0 = 0; // Make output
{ RC0 = 0; // Make value zero
RC0 = ~RC0; // Toggle RC0 pin
while(1)
INTF = 0; // clear the interrupt {
} }
} }
void InitExternal_INT(void)
{
TRISBbits.TRISB0 = 1; // Make RB0 pin as input
INTCON |= 0x90; // Enable Global + INT interrupt
OPTION_REG |= 0x40; // Make INT as posedge triggered
}

23/04/2023 46
Timers
• Timers are used to measure the time or generate the accurate time delay.
• Timer is nothing but a simple binary counter that can be configured to count clock
pulses(Internal/External).
• Once it reaches the Max value, it will roll back to zero setting up an Overflow flag and
generates the interrupt if enabled.
• There are a lot of systems that perform various processes that depend on time.
• Simple example of this process is the digital wristwatch. The role of this electronic
system is to display time in a very precise manner and change the display every second
(for seconds), every minute (for minutes) and so on
• The microcontroller PIC16F877A has 3 different timers which can be used in many
tasks, such as
✔ generating timing signals,
✔ causing interrupts to be generated at specific time intervals,
✔ measuring frequency and time intervals,
✔ “delay procedure” to implement some delay in the program,
✔ and so on.
• The three time modules are:
✔ Timer0
✔ Time1
✔ Timer2

23/04/2023 47
Basic Components of Timer Module
• MAIN COMPONENTS OF A TIMER/COUNTER MODULE

• The source signal can be external or internal clock sources.


• The time taken for the Timer register depends on the value of Prescaler and the
value of the Fosc.
• The Fosc stands for Frequency of the Oscillator, it is the frequency of the Crystal
used.
• Prescaler is a name for the part of a microcontroller which divides oscillator clock
before it will reach logic that increases timer status.
• The range of the prescaler id is from 1 to 256 and the value of the Prescaler can be
set using the OPTION Register
• Postscaler scales the timer output so that interrupt occurs after every two or more
than two timer loops instead of every loop
23/04/2023 48
Timer 0:
• Timer 0 module timer/counter has the following features:
✔ 8-bit timer/counter
✔ Readable and writable
✔ 8-bit software programmable prescaler
✔ Internal (4 Mhz) or external clock select
✔ Interrupt on overflow from FFh to 00h
✔ Edge select (rising or falling) for external clock
• Timer0 Registers
✔ OPTION_REG: This registers is used to configure the TIMER0 Prescalar, Clock
Source etc
✔ TMR0: This register holds the timer count value which will be incremented depending
on prescalar configuration.
✔ INTCON: This register contains the Timer0 overflow flag(TMR0IF) and
corresponding Interrupt Enable flag(TMR0IE).

23/04/2023 49
Timer0: OPTION_REG

Note: There is only one prescaler available which is


mutually exclusively shared between the Timer0
module and the Watchdog Timer. A prescaler
assignment for the Timer0 module means that there
is no prescaler for the Watchdog Timer and vice
versa. This prescaler is not accessible but can be
configured using PS2:PS0 bits of OPTION_REG.
23/04/2023 50
Timer0: INTCON

• GIE: Global Interrupt Enable bit


1-Enables all unmasked interrupts
0-Disables all interrupts
• PEIE: Peripheral Interrupt Enable bit
1-Enables all unmasked peripheral interrupts
0-Disables all peripheral interrupts
• TMR0IE: TMR0 Overflow Interrupt Enable bit
1-Enables the TMR0 interrupt
0-Disables the TMR0 interrupt
• INTE: NA for Timers
• RBIE: NA for Timers
• TMR0IF: TMR0 Overflow Interrupt Flag bit
1-TMR0 register has overflowed (must be cleared in software)
0-TMR0 register did not overflow
• INTF: NA for Timers
• RBIF: NA for Timers

23/04/2023 51
23/04/2023 52
Steps for configuring and using the Timer0
• Below are the steps for configuring and using the Timer0 for delay
generation:
✔ Calculate the Timer Count for the required delay.
✔ Set the Presaclar bits in OPTION_REG as per the delay calculations.
✔ Clear the PSAbit for using the prescalar.
✔ Select the Clock Source Internal/External using TOCS bit.
✔ Load the timer value into TMRO register.
✔ Enable the Timer0 Interrupt by setting TMR0IE bit
✔ Enable the Global and Peripheral interrupts by setting GIE and PIE bits
• Delay Calculations for 1ms @20Mhz with Prescalar as 32:
RegValue = 256-(Delay * Fosc)/(Prescalar*4))
= 256-((1ms * 20Mhz)/(32*4)) = 256-156
=100
TMR0=100; OPTION_REG = (1<<2);

23/04/2023 53
Blink the LEDs with 1ms delay Using Timer0
char value = 0x02;
#define SBIT_PS2 2
void interrupt timer_isr()
{
if(TMR0IF==1)
{
value=~value; // complement the value for blinking the LEDs
TMR0 = 101; //Load the timer Value*
//(Note: Timervalue is 101 instaed of 100 as the TImer0 needs two instruction Cycles to start incrementing TMR0 */
TMR0IF=0; // Clear timer interrupt flag
}
}}

void main()
{
TRISC=0x00; //COnfigure PORTD as output to blink the LEDs
OPTION_REG = (1<<SBIT_PS2); // Timer0 with external freq and 32 as prescalar
TMR0=100; // Load the time value for 1ms delay
TMR0IE=1; //Enable timer interrupt bit in PIE1 register
GIE=1; //Enable Global Interrupt
PEIE=1; //Enable the Peripheral Interrupt
while(1)
{
PORTC = value;
}
}

23/04/2023 54
Timer 1:
• The timer TMR1 module is 16-bits timer/counter with the following
features:
✔ 16-bit timer/counter with two 8-Bit register TMR1H/TMR1L
✔ Readable and writable
✔ software programmable prescaler upto 1:8
✔ Internal or external clock select
✔ Interrupt on overflow from FFFFh to 00h
✔ Edge select for external clock
• The below table shows the registers associated with PIC16f877A Timer1
module.

23/04/2023 55
Timer1:T1CON Register

• T1CKPS1:T1CKPS0:Timer1 Input Clock Prescale Select bits


11 = 1:8 prescale value
10 = 1:4 prescale value
01 = 1:2 prescale value
00 = 1:1 prescale value
• T1OSCEN: Timer1 Oscillator Enable Control bit
1-Oscillator is enabled
0-Oscillator is shut-off
• T1SYNC: Timer1 External Clock Input Synchronization Control bit
1-Do not synchronize external clock input
0-Synchronize external clock input
• TMR1CS: Timer1 Clock Source Select bit
1-External clock from pin RC0/T1OSO/T1CKI (on the rising edge)
0-Internal clock (FOSC/4)
• TMR1ON: Timer1 On bit
1-Enables Timer1
0-Stops Timer1
23/04/2023 56
23/04/2023 57
Steps for configuring and using the Timer1
• Below are the steps for configuring and using the Timer1 for delay
generation:
✔ Calculate the Timer Count for the required delay.
✔ Set the Presaclar bits in T1CON as per the delay calculations.
✔ Select the Clock Source Internal/External using TMR1CS bit.
✔ Load the timer value into TMR1H,TMR1L register.
✔ Enable the Timer1 Interrupt by setting TMRIE bit
✔ Enable the Global and Peripheral interrupts by setting GIE and PIE bits
✔ Finally start the timer by setting TMR1ON bit
• Delay Calculations for 100ms @20Mhz with Prescalar as 8:
RegValue = 65536-(Delay * Fosc)/(Prescalar*4))
= 65536-((100ms * 20Mhz)/(8*4))
= 3036 = 0x0BDC
// Load the time value(0x0BDC) for 100ms delay
TMR1H=0x0B;
TMR1L=0xDC;

23/04/2023 58
Blink the LEDs with 100ms delay Using Timer1
char value = 0;
void main()
#define SBIT_PS1 5
{
#define SBIT_PS0 4
TRISD=0x00; //COnfigure PORTD as output to blink the LEDs
void interrupt timer_isr()
T1CON = (1<<SBIT_PS1) | (1<<SBIT_PS0); // Timer0 with external freq and 8 as prescalar
{
TMR1H=0x0B; // Load the time value(0xBDC) for 100ms delay
if(TMR1IF==1)
TMR1L=0xDC;
{
TMR1IE=1; //Enable timer interrupt bit in PIE1 register
value=~value; // complement the value for blinking the LEDs
GIE=1; //Enable Global Interrupt
TMR1H=0x0B; // Load the time value(0xBDC) for 100ms delay
PEIE=1; //Enable the Peripheral Interrupt
TMR1L=0xDC;
TMR1ON = 1; //Start Timer1
TMR1IF=0; // Clear timer interrupt flag
while(1)
}
{
}
PORTD = value;
}
}

23/04/2023 59
Timer2
• The Timer2 module is an 8-bit timer/counter with the following features:
✔ 8-bit timer/counter
✔ Readable and writable
✔ Software programmable prescaler/PostScaler upto 1:16
✔ Interrupt on overflow from FFh to 00h
• Postscaler scales the timer output from 1:1 to 1:16 so that interrupt occurs after
every 1….16 timer loops instead of every loop
• The below table shows the registers associated with PIC16f877A Timer2
module.

23/04/2023 60
Timer2:T2CON Register

• TOUTPS3:TOUTPS0: Timer2 Output Postscale Select bits


0000 = 1:1 postscale
0001 = 1:2 postscale
0010 = 1:3 postscale



1111 = 1:16 postscale
• TMR2ON: Timer2 On bit
1-Timer2 is on
0-Timer2 is off
• T2CKPS1:T2CKPS0: Timer2 Clock Prescale Select bits
00 = Prescaler is 1
01 = Prescaler is 4
1x = Prescaler is 16

23/04/2023 61
23/04/2023 62
Steps for configuring and using the Timer2
• Below are the steps for configuring and using the Timer2 for delay generation:
✔ Calculate the Timer Count for the required delay.
✔ Set the Prescaler bits in T2CON as per the delay calculations.
✔ Load the timer value into TMR2 register.
✔ Enable the Timer2 Interrupt by setting TMR2IE bit
✔ Enable the Global and Peripheral interrupts by setting GIE and PIE bits
✔ Finally start the Timer2 by setting TMR2ON bit
• Generating 1sec delay using Timer2, @20Mhz clock:
• As the timer2 is 8-bit and supports 1:16 prescalar, it is not possible to directly generate
the delay of 1sec. The max delay with 1:16 prescaler will be:
Delay = 256 * (Prescaler*4)/Fosc
= 256 * 16*4/20Mhz
=819us
• Now 500us can be generated using timers which will be used to increment a counter
2000 times to get 1sec delay.
Delay Calculations for 500usec @20Mhz with Prescalar as 16:
RegValue = 256-(Delay * Fosc)/(Prescalar*4))
= 256-((500us* 20Mhz)/(16*4))
= 256-156=100

23/04/2023 63
Blink the LEDs with 1s(500us x2000times) delay Using
Timer2
#define SBIT_T2CKPS1 1
void main()
char value = 0;
{
int count = 0;
TRISD=0x00; //COnfigure PORTD as output to blink the LEDs
void interrupt timer_isr()
{
T2CON = (1<<SBIT_T2CKPS1); // Timer2 with external freq and 16 as prescalar
if(TMR2IF==1)
TMR2=100; // Load the timer value for 500us delay
{
TMR2IE=1; //Enable timer interrupt bit in PIE1 register
if(count>=2000) //500us * 2000=1000000us=1sec
GIE=1; //Enable Global Interrupt
{
PEIE=1; //Enable the Peripheral Interrupt
count=0;
TMR2ON = 1;
value=~value; // complement the value for blinking the LEDs
while(1)
/*Load the timer Value, (Note: Timervalue is 101 instead of 100 as the Timer2
needs two instruction Cycles to start incrementing TMR2 */ {

} PORTD = value;

else }

{ }

// Keep incrementing the count till it reaches 2000 to generate 1sec delay
count++;
}
TMR2 = 101;

TMR2IF=0; // Clear timer interrupt flag


}
}

23/04/2023 64
CAPTURE/COMPARE/PWM (CCP)MODULES
• Capture-Compare-Pulse-Width-Module (CCP) is a special module designs
for modulation and waveform generation applications.
✔ Capture module causes the contents of an internal 16 bit timer, upon detecting an n th rising or falling
edge, to be written to on-board special function registers
✔ Compare module generates an interrupt, or change on output pin, when Timer 1
matches a pre-set comparison value
✔ PWM module generate a square waveform with a specified period and duty cycle.
• PIC16F877A microcontroller has two independent Capture/Compare/PWM (CCP)
modules, named as CCP1 and CCP2.
• Each CCP module has two 8-bit registers (CCPxH, CCPxL) that can be use as:
✔ 16 bit Capture Register
✔ 16 bit Compare Register
✔ 10-bit PWM Register

23/04/2023 65
CAPTURE/COMPARE Module

CAPTURE Module: Reading Assignment

COMPARE Module: Reading Assignment

23/04/2023 66
PWM Module
• PIC has two PWM module with a resolution of 10-bits.
• The 8-MSB bits are stored in CCPRxL and remaining 2-bits in CCPxCON
register.

• The registers associated with PIC16F877A PWM.

• Note: Where x will 1 for PWM module one and 2 for PWM module two.

23/04/2023 67
CCPxCON: PWM Registers

• CCPxX:CCPxY: PWM Least Significant bits


These bits are the two LSBs of the PWM duty cycle. The eight MSBs are found in
CCPRxL.
• CCPxM3:CCPxM0: CCPx Mode Select bits
0000 - Capture/Compare/PWM disabled (resets CCPx module)
0100 - Capture mode, every falling edge
0101 - Capture mode, every rising edge
0110 - Capture mode, every 4th rising edge
0111 - Capture mode, every 16th rising edge
1000 - Compare mode, set output on match (CCPxIF bit is set)
1001 - Compare mode, clear output on match (CCPxIF bit is set)
1010 - Compare mode, generate software interrupt on match (CCPxIF bit is set,
CCPx pin is unaffected)
1011 - Compare mode, trigger special event (CCPxIF bit is set, CCPx pin is
unaffected);
11xx - PWM mode

23/04/2023 68
Terminologies about PWM
• Ton: Time for which the signal is ON/HIGH.
• Toff: Time for which the signal is OFF/LOW.
• Period: The cycle time of the signal which is the sum of Ton and Toff period.
Period= Ton+Toff
Freq of Pwm signal = 1/Period.
• Duty Cycle: The percentage of time for which the PWM signal will be
ON/HIGH.
• DutyCycle = (Ton/(Ton+Toff))*100 = (Ton/Period) * 100

23/04/2023 69
Terminologies about PWM
• Lets relate the above concepts with the PIC registers.
• PIC uses TIMER2 for generating the PWM signals.
• Period:
✔ PR2 register is used to specify the PWM Period.
✔ The PWM period can be calculated using the following formula.
 PWM Period = [(PR2) + 1] * 4 * TOSC * (TMR2 Prescale Value)
 PR2 = ( PWM Period / ( TOsc x 4 x TMR2 Prescaler ) ) – 1
 TOsc = 1 /FOSC
• DutyCycle:
✔ The DutyCycle is represented by 10 bits
✔ CCPR1L and CCP1CON<5:4> are used to specify the DutyCycle.
✔ The CCPR1L contains the eight MSBs and the CCP1CON<5:4> contains the two LSBs.
✔ PWM Duty Cycle= (CCPR1L : CCP1CON<5:4>)*Tosc* TMR2 Prescaler
• PWM Signal Generation:
✔ Once the PWM is configured and Timer2 is enabled, TMR2 starts incrementing depending on
the prescalar.
• Once the TMR2 value is equal to dutyCycle (CCPR1L+CCP1CON<5:4>) the
PWM pin will be pulled LOW.
• The timer still continues to increment till it matches with the period PR2. After
which the PWM pin will be pulled HIGH and TMR2 is reset for next cycle.

23/04/2023 70
Example
• Example: PWM pulses must be generated from pin CCP1 of a
PIC16F877A microcontroller. The required pulse period is 44us and the
required duty cycle is 50%. Assuming that the microcontroller operates
with a 4MHz crystal, calculate the values to be loaded into the various
registers. Assuming a timer prescaler factor of 4,

The required steps are summarized as


follows:
• Load Timer 2 with prescaler of 4 (i.e.,
load T2CKPS) with 00000101 (i.e.,
05H).
• Load 0AH into PR2.
• Load 16H into CCPR1L.
• Load 0 into TRISC (make CCP1 pin
output).
• Load 0CH into CCP1CON just to select
PWM

23/04/2023 71
PIC16f877a PWM block diagram and output signal
generation

23/04/2023 72
Steps to Configure PWM
• Configure the CCP1 module for PWM operation.
• Set the PWM period by writing to the PR2 register.
• Set the PWM duty cycle by writing to the CCPR1L register and
CCP1CON<5:4> bits.
• Make the CCP1 pin an output by clearing the TRISC<2> bit.
• Set the TMR2 prescale value and enable Timer2 by writing to T2CON.

23/04/2023 73
Program to demonstrates the LED fading and
Varying DC motor Speed using PWM signals
int main()
#include <xc.h>
{
char dutyCycle = 0;
void delay(int cnt)
TRISC = 0x00; // Configure PORTC as output(RC2-PWM1, RC1-PWM2)
{
while (cnt--); CCP1CON = 0x0F; // Select the PWM mode.
} PR2 = 100; // Set the Cycle time to 100 for varying the duty cycle from 0-100
CCPR1L = 50; // By default set the dutyCycle to 50
TMR2ON = 1; //Start the Timer for PWM generation

while (1) {
for (dutyCycle = 0; dutyCycle < 100; dutyCycle++) // Keep increasing the dutyCyle to increase the brightness of LED
{
CCPR1L = dutyCycle;
delay(1000);
}
for (dutyCycle = 100; dutyCycle > 0; dutyCycle--) // Keep reducing the dutyCyle to decrease the brightness of LED
{
CCPR1L = dutyCycle;
delay(1000);
}
}
}

23/04/2023 74
Analog-to-Digital Converter (A/D) Module
• The A/D module converts an analog input voltage into a digital number so
it can be processed by a microcontroller or any other digital system.
• PIC16F877A has an inbuilt 10 bit Successive Approximation ADC which is
multiplexed among 8 input pins.
• The A/D module has high and low-voltage reference input that is software
selectable to some combination of VDD, VSS, RA2 or RA3.
• With 5v as the Vref the resolution of PIC16f877A ADC can be determined as
below:
✔ Resolution of ADC = Vref/(210-1) = 5/1023 =0.004887 = 4.887mv
• Port A and Port E of ADC input pins multiplexed with other GPIO pins.
• The ADC pin can be enabled by configuring the corresponding ACON1
register.
• When the ADC function is selected for a pin ,then other Digital signals are
disconnected from the ADC input pins.

23/04/2023 75
ADC Pins and Registers

• The registers associated with PIC16F877A ADC

23/04/2023 76
ADCON0:ADC Registers

23/04/2023 77
ADCON1

23/04/2023 78
ADC Block Diagram

23/04/2023 79
Read the ADC value of channel0 and Display it on LCD
#include <xc.h> int main()
#define SBIT_ADON 0 {
#define SBIT_CHS0 3 int adcValue=0;
#define SBIT_ADFM 7 /*Configure PORTB and PORTD as output to display the ADC values on
LEDs*/
void delay(int cnt)
TRISB = 0x00;
{
TRISD = 0x00;
while(cnt--);
ADC_Init(); //Initialize the ADC module
}
while(1)
void ADC_Init()
{
{
// Read the ADC value of channel zero
ADCON0=0x00; // sampling freq=osc_freq/2,ADC off initially
// All pins are configured as Analog pins and ADC result is right justified
adcValue = ADC_Read(0);
ADCON1=(1<<SBIT_ADFM);
//Adc value displayed on LEDs connected to PORTB,PORTD
}
PORTB = (adcValue & 0xff);
int ADC_Read(int adcChannel)
// PORTB will display lower 8-bits and PORTD higher 2-bits
{
PORTD = (adcValue>>8) & 0x03;
//select required channel and turn ON adc
}
ADCON0 = (1<<SBIT_ADON) | (adcChannel<SBIT_CHS0);
}
delay(1000); //Acquisition Time(Wait for Charge Hold Capacitor to get charged )
GO=1; // Start ADC conversion
while(GO_DONE==1); // Wait for the conversion to complete
// GO_DONE bit will be cleared once conversion is complete
return((ADRESH<<8) + ADRESL); // return right justified 10-bit result
}

23/04/2023 80
Serial Communication
• PIC16F877A comes with inbuilt USART(Universal Synchronous Asynchronous Receiver
Transmitter) which can be used for Synchronous/Asynchronous communication to transmit
and receive data.
• USART is a two wire communication system in which the data flow serially.
• USART is also a full-duplex communication, means you can send and receive data at the
same time which can be used to communicate with peripheral devices, such as personal
computers.
• The USART can be configured in the following modes:
✔ Asynchronous (full-duplex)
✔ Synchronous – Master (half-duplex)
✔ Synchronous – Slave (half-duplex)
• Synchronous communication:
✔ The information is transmitted from the transmitter in sequence, bit after bit, with fixed baud rate, when
the clock frequency along with the bits are transmitted to the receiver.
✔ This means that the transmitter and the receiver are synchronized between them by the same clock
frequency.
• Asynchronous communication:
✔ In this case, the information is divided into frames, in the size of byte. Each one of the frame has a
“Start” bit and a “Stop” bit.
✔ “Start” bit marks the beginning of a new frame, “Stop” bit marks the end. Frames of information must
not necessarily be transmitted at equal time space, since they are independent of the clock.
• In this tutorial we will see how to configure the USART module to work as Asynchronous
mode with 8-bit communication system, which is called UART.

23/04/2023 81
UART Registers
• The registers associated with PIC16F877A UART.

• To allow serial communication with the PIC16F877A, we need to set


different parameters within 2 registers(TXSTA and RCSTA):

23/04/2023 82
TXSTA: UART Register

• CSRC: Clock Source Select bit


Asynchronous mode : Don’t care.
• TX9: 9-bit Transmit Enable bit
1 = Selects 9-bit transmission
0 = Selects 8-bit transmission
• TXEN: Transmit Enable bit
1 = Transmit enabled
0 = Transmit disabled
• SYNC: USART Mode Select bit
1 = Synchronous mode
0 = Asynchronous mode
• BRGH: High Baud Rate Select bit
1 = High speed
0 = Low speed
• TRMT: Transmit Shift Register Status bit
1 = TSR empty
0 = TSR full
• TX9D: 9th bit of Transmit Data, can be Parity bit

23/04/2023 83
RCSTA: UART Register

• SPEN: Serial Port Enable bit


1 = Serial port enabled (configures RC7/RX/DT and RC6/TX/CK pins as serial port pins)
0 = Serial port disabled
• RX9: 9-bit Receive Enable bit
1 = Selects 9-bit reception
0 = Selects 8-bit reception
• SREN: Single Receive Enable bit
Asynchronous mode : Don’t care.
• CREN: Continuous Receive Enable bit
Asynchronous mode:
1 = Enables continuous receive
0 = Disables continuous receive
• ADDEN: Address Detect Enable bit
Asynchronous mode 9-bit (RX9 = 1):
1 = Enables address detection, enables interrupt and load of the receive buffer when RSR is set
0 = Disables address detection, all bytes are received and ninth bit can be used as parity bit
• FERR: Framing Error bit
1 = Framing error (can be updated by reading RCREG register and receive next valid byte)
0 = No framing error
• OERR: Overrun Error bit
1 = Overrun error (can be cleared by clearing bit CREN)
0 = No overrun error
• RX9D: 9th bit of Received Data (can be parity bit but must be calculated by user firmware)

23/04/2023 84
Baud Rate Calculation
• The main criteria for UART communication is its baud rate.
• Both the devices Rx/Tx should be set to same baud rate for successful
communication.
• This can be achieved by SPBRG register.
• SPBRG is a 8-bit register which controls the baud rate generation.
• Given the desired baud rate and FOSC, the nearest integer value for the
SPBRG register can be calculated using the below formula.
• BRGH = 1 High Speed
SPBRG = (Fosc / (16 * BaudRate)) - 1
• BRGH = 0 Low Speed
SPBRG = (Fosc / (64 * Baud rate)) - 1

23/04/2023 85
List of standard BaudRates and the SPBRG values.

23/04/2023 86
Steps To Send Char
• Wait till the previous char is transmitted. TXIF will be set when the TXREG
is empty.
• Clear the TXIF for next cycle.
• Load the new char to be transmitted into TXREG.

void UART_TxChar(char ch)


{
while(TXIF==0); // Wait till the transmitter register becomes empty
TXIF=0; // Clear transmitter flag
TXREG=ch; // load the char to be transmitted into transmit reg
}

23/04/2023 87
Steps To Receive Char
• Wait till the Data is received. RCIF will be set once the data is received in
RCREG register.
• Clear the receiver flag(RCIF) for next cycle.
• Copy/Read the received data from RCREG register.

char UART_RxChar()
{
while(RCIF==0); // Wait till the data is received
RCIF=0; // Clear receiver flag
return(RCREG); // Return the received data to calling function
}

23/04/2023 88
Transmit and receive the chars at 9600 baudrate with
20Mhz clock.
#include <xc.h> int main()
#define SBIT_TXEN 5 {
#define SBIT_SPEN 7 char i,a[]={"Welcome to Pic Serial Comm, Type the char to be echoed: "};
#define SBIT_CREN 4 char ch;
void UART_Init(int baudRate) UART_Init(9600); //Initialize the UART module with 9600 baud rate
{ for(i=0;a[i]!=0;i++)
TRISC=0x80; // Configure Rx pin as input and Tx as output {
// Asynchronous mode, 8-bit data & enable transmitter UART_TxChar(a[i]); // Transmit predefined string
TXSTA=(1<<SBIT_TXEN); }
// Enable Serial Port and 8-bit continuous receive while(1)
RCSTA=(1<<SBIT_SPEN) | (1<<SBIT_CREN); {
// baud rate @20Mhz Clock ch = UART_RxChar(); // Receive a char from serial port
SPBRG = (20000000UL/(long)(64UL*baudRate))-1;} UART_TxChar(ch); // Transmit the received char
void UART_TxChar(char ch) }
{ }
while(TXIF==0); // Wait till the transmitter register becomes empty
TXIF=0; // Clear transmitter flag
TXREG=ch; // load the char to be transmitted into transmit reg
}
char UART_RxChar()
{
while(RCIF==0); // Wait till the data is received
RCIF=0; // Clear receiver flag
return(RCREG); // Return the received data to calling function
} 23/04/2023 89
Memory Organization
• There are three memory blocks in each of the PIC16F87XA devices. They are
✔ Program memory
✔ Data memory and
✔ Data EEPROM
• Program Memory - A memory that contains the program after we've burned it.
✔ Program Counter executes commands stored in the program memory, one after the other.
• Data Memory – This is RAM memory type, which contains a special registers like
SFR (Special Faction Register) and GPR (General Purpose Register).
✔ The variables that we store in the Data Memory during the program are deleted after we turn
of the microcontroller.
• Data EEPROM (Electrically Erasable Programmable Read-Only Memory) - A
memory that allows storing the variables as a result of burning the written program.
• Program Memory and Data EEPROM they are non-volatile memories, which store
the information even after the power is turn off.
• Data Memory does not save the information because it needs power in order to
maintain the information stored in the chip.

23/04/2023 90
PIC16F877A Program Memory
• This memory is used to store the program after we burn it to the microcontroller.
• The PIC16F876A/877A devices have 8K words x 14 bits of Flash program memory that
can be electrically erased and reprogrammed.
• The PIC16F87XA devices have a 13-bit program counter capable of addressing an 8K
word x 14 bit program memory space.
• Each time we burn program into the microcontroller, we erase an old program and write a
new one.
• The PIC16F87XA family has an 8-level deep x 13-bit wide hardware stack.
✔ The stack space is not a part of either program or data space and the stack pointers are not
readable or writable.
✔ In the PIC microcontrollers, this is a special block of RAM memory used only for this purpose.
▪ The CALL instruction is used to jump to a subroutine, which must be terminated with the RETURN
instruction.
▪ CALL has the address of the first instruction in the subroutine as its operand.
▪ When the CALL instruction is executed, the destination address is copied to the PC.
▪ The PC is PUSHed onto the stack when a CALL instruction is executed, or an interrupt causes a branch. The
stack is POP’ed in the event of a RETURN, RETLW or a RETFIE instruction execution.
▪ The stack operates as a circular buffer. This means that after the stack has been PUSHed eight times, the ninth
push overwrites the value that was stored from the first push. The tenth push overwrites the second push (and
so on).
• Each time the main program starts execution at address 0000 – Reset Vector.
• The address 0004 is “reserved” for the “interrupt service routine” (ISR).

23/04/2023 91
23/04/2023 92
PIC16F87XA Data Memory Organization
• The data memory is partitioned into multiple banks which contain the General
Purpose Registers and the Special Function Registers.
• The PIC16F877A chip only has four banks (BANK 0, BANK 1, BANK 2,
and BANK3). Each bank holds 128 bytes of addressable memory.
• Each bank extends up to 7Fh (128 bytes). The lower locations of each bank
are reserved for the Special Function Registers.
• Above the Special Function Registers are General Purpose Registers,
implemented as static RAM. While program is being executed, it is working
with the particular bank. The default bank is BANK0.
• To access a register that is located in another bank, one should access it inside
the program. There are special registers which can be accessed from any
bank, such as STATUS register.
• The General Purpose Registers file can be accessed either directly, or
indirectly, through the File Select Register (FSR).

23/04/2023 93
23/04/2023 94
Data EEPROM

Data EEPROM: Reading Assignment

23/04/2023 95
Interfacing
• Push Button
• LED
• Analog sensors
• 7 Segment Display interfacing
• 2x16 LCD interfacing
• Keypad Interfacing

23/04/2023 96
7 Segment Display interfacing
• Seven-segment displays are commonly used as alphanumeric displays by logic and computer
systems.
• A seven segment display is an arrangement of 7 LEDs
• 7-segment displays come in two flavors:
 common anode and
 common cathode.
• A common anode 7-segment display has all of the anodes tied together to VCC(5v). Thus the
segments a to g needs a logic LOW signal(GND) in order to glow.

• A common cathode 7-segment display has all the cathodes tied together to GND. Thus the
segments a to g needs a logic High signal(5v) in order to glow.

23/04/2023 97
Interfacing common cathode 7 Segment with
PIC16F877A

• Equivalent PORTC values • PORTC=0x6D, for 5


• PORTC=0x3F, for 0
• PORTC=0x7D, for 6
• PORTC=0x06, for 1
• PORTC=0x5B, for 2 • PORTC=0x07, for 7
• PORTC=0x4F, for 3 • PORTC=0x7F, for 8
• PORTC=0x66, for 4 • PORTC=0x6F, for 9

23/04/2023 98
Interfacing 2x16 LCD with PIC16F877A
• The 2x16 LCD has 2 lines with 16 chars on Pin Number Symbol Pin Function
each lines.
1 VSS Ground
• It supports all the ASCII chars and is
basically used for displaying the alpha 2 VCC +5v
numeric characters.
• Each character is displayed in a matrix of 5x7 3 VEE Contrast adjustment (VO)
pixels.
4 RS Register Select. 0:Command, 1: Data
• Apart from the voltage supply connections
the important pins from the programming 5 R/W Read/Write, R/W=0: Write & R/W=1:
perspective are Read
✔ the data lines(8-bit Data bus),
✔ Register select, 6 EN Enable. Falling edge triggered
✔ Read/Write and 7 D0 Data Bit 0
✔ Enable pin.
8 D1 Data Bit 1
9 D2 Data Bit 2
10 D3 Data Bit 3
11 D4 Data Bit 4
12 D5 Data Bit 5
13 D6 Data Bit 6
14 D7 Data Bit 7/Busy Flag
15 A/LED+ Back-light Anode(+)
16 K/LED- Back-Light
23/04/2023 Cathode(-) 99
Pin Configuration of 2x16 LCD
• Apart from the voltage supply connections the important pins from the programming perspective are
✔ The Data lines(8-bit Data bus),
✔ The Register select,
✔ The Read/Write and
✔ The Enable pin.
• Data Bus:
✔ an alpha numeric lcd has a 8-bit data bus referenced as D0-D7.
✔ As it is a 8-bit data bus, we can send the data/cmd to LCD in bytes.
✔ It also provides the provision to send the the data/cmd in chunks of 4-bit, which is used when there are limited number of
GPIO lines on the microcontroller.
• Register Select(RS):
✔ The LCD has two register namely a Data register and Command register.
✔ Any data that needs to be displayed on the LCD has to be written to the data register of LCD.
✔ Command can be issued to LCD by writing it to Command register of LCD.
✔ This signal is used to differentiate the data/cmd received by the LCD.
✔ If the RS signal is LOW then the LCD interprets the 8-bit info as Command and writes it Command register and performs
the action as per the command.
✔ If the RS signal is HIGH then the LCD interprets the 8-bit info as data and copies it to data register. After that the LCD
decodes the data for generating the 5x7 pattern and finally displays on the LCD.
• Read/Write(RW):
✔ This signal is used to write the data/cmd to LCD and reads the busy flag of LCD. For write operation the RW should
be LOW and for read operation the R/W should be HIGH.
• Enable(EN):
✔ This pin is used to send the enable trigger to LCD. After sending the data/cmd, Selecting the data/cmd register, Selecting
the Write operation. A HIGH-to-LOW pulse has to be send on this enable pin which will latch the info into the LCD
register and triggers the LCD to act accordingly.

23/04/2023 100
Steps
• Steps for Sending Command: • Steps for Sending Data:
✔ step1: Send the I/P command to LCD. ✔ step1: Send the character to LCD.
✔ step2: Select the Control Register by making ✔ step2: Select the Data Register by making
RS low. RS high.
✔ step3: Select Write operation making RW ✔ step3: Select Write operation making RW
low. low.
✔ step4: Send a High-to-Low pulse on Enable ✔ step4: Send a High-to-Low pulse on
Enable PIN with some delay_us.
PIN with some delay_us.

23/04/2023 101
Some of Important Commands

Hex Code Command to LCD instruction Register

0x01 Clear display screen


0x08 Display off, cursor off
0x0A Display off, cursor on
0x0C Display on, cursor off
0x0E Display on, cursor blinking
0x0F Display on, cursor blinking
0x80 Set cursor to beginning (1st line)
0xC0 Set cursor to beginning (2nd line)
0x38 Set 8 bit 2 lines and 5×7 matrix
0x30 Set 8 bit 1 lines and 5×7 matrix
0x20 Set 4 bit 2 lines and 5×7 matrix
0x28 Set 4 bit 1 lines and 5×7 matrix
23/04/2023 102
23/04/2023 103
Keypad Interface
• A twelve-key keypad usually consists of a matrix of twelve switches
• Three lines connect the columns while four lines connect the rows.
• When a key is pressed, one column and one row are connected.

• The PIC must use its software to scan each column-line and look for a
row-line that is connected, if, and when, a switch is pressed.

23/04/2023 104
Interfacing Keypad

23/04/2023 105
Assignment #1
• Design a simple temperature control system for small room using PIC16F877A.
The task of the system is to maintain the room temperature at 25 0C at any time.
It achieves this by rotating the fun with different speed value. The fun stays off
when the temperature is below 250C. when the temperature is above 250C and
below 270C the fun starts rotate with small speed (1/3 of the maximum speed).
when the temperature is above 270C and below 300C the fun starts rotate with
medium speed (2/3 of the maximum speed). when the temperature is above
300C the fun starts rotate with maximum speed. To indicate the temperature is
cold, LED is used which turns on when the temperature is below 25 0C and off
when the temperature is above 250C. LCD is also used to display the value of
the temperature sensed.
• The system uses linear LM35for measuring the temperature.
• Points to do:
✔ Draw the block diagram which shows the whole system interconnection
✔ Write the PIC16F877A firmware code to implement the temperature control
✔ Using Proteus, design the schematic diagram of the device
✔ Provide a Bill Of Material file
✔ Using Proteus, design the board layout of the device

23/04/2023 106
Assignment #2
• Design a PIC16F877A microcontroller based automatic door opening
embedded system which is powered by 5V. This Design is used to sense
any body movement nearby the door using passive infrared sensor(PIR) to
open and close the door. Generally, a human body emits infrared energy
which is detected by the PIR sensor from a particular distance. This signal
which is detected by the sensor is fed to a microcontroller to function a
door motor through motor driver IC (L293D). When a body reaches the
operating range of the PIR sensor, it sends a signal to the microcontroller
to open and close the door.
Please use a 5V DC motor.
• Points to do:
✔ Design a detailed and completed block diagram of the device.
✔ Write a the firmware code of the microcontroller. (4 Points)
✔ Using Proteus, design the schematic diagram of the device
✔ Provide a Bill Of Material file
✔ Using Proteus, design the board layout of the device

23/04/2023 107

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy