Unit II

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

Unit II:: PIC I/O Ports and Timer (06 Hrs)

I/O Port : I/O Port structure with programming: I/O Port structure, I/O Port
programming, I/O Bit manipulation Programming.

Timer/Counter: Registers used for Timer/Counter operation, Delay calculations,


Programming of Timers using Embedded C.

Case Study:Traffic light signal controller using Timer/Count

Programmed I/O
Programmed input–output (also programmed input/output, programmed I/O, PIO) is a
method of data transmission, via input/output (I/O), between a central processing unit
(CPU) and a peripheral device, such as a network adapter or a Parallel ATA storage
device.

Example Case Study: Street Lights That Glow on Detecting Vehicle Movement | EEE
Projects
https://www.youtube.com/watch?v=wjrVzekkSNs
5 ports: Port A, Port B, Port C, Port D, Port E: Total 33 Pins
Pin 1: MCLR: Master Clear Input (RESET), Reset Pin Microcontroller get by default 0
signal
Pin 13: Clock:
Pin 11,32: VDD : VDD pins are normally connected to +5 V
Pin 12, 31: VSS: VSS (ground) pins
Pin 2,3,4,5,6,7: Port: A : Total 6
Pin 33,34,35,36,37,38,29,40: Port B: Total 8
Pin: 15,16,17,18,23,24,25,26: Port C :Total 8
Pin 19,20,21,22,27,28,29,30: Port D :Total 8
Pin 8,9,10: Port E: Total 3

URL:https://www.youtube.com/watch?v=YkPQGy5soG0

USE INPUT OUTPUT PORTS OF PIC18F452 MICROCONTROLLER

USE INPUT OUTPUT PORTS OF PIC18F452 MICROCONTROLLER:

URL:
https://microcontrollerslab.com/use-input-output-ports-pic18f452/

PIC18F452 microcontroller has a number of input/output pins which are used for
connection with external devices. It has total 40 pins. Out of these 40 pins, 34 pins can
be used as input output pins.These pins are grouped into five which are called PORTS
denoted by A, B, C, D and E. Here in this article we will learn how to use I/O Ports of
PIC18F452.

 Port A consists of seven pins named as RA0-RA6


 Port B consists of eight pins named as RB0-RA7
 Port C consists of eight pins named as RC0-RC7
 Port D consists of eight pins named as RD0-RD7
 Port E consists of three pins named as RE0-RE2

Some pins of the I/O ports are multiplexed with an alternate function from the
peripheral features on the device. If a pin is used as any other function then it may not
be used as a general purpose I/O pin. Here we will just restrict with the input output
features of ports.
REGISTERS:
Each port has three registers for its operation. These registers are
• TRIS register (data direction register)
• PORT register (reads the levels on the pins of the device)
• LAT register (output latch)
1.TRIS REGISTER:
TRIS is a data direction register. Setting TRIS bit for corresponding port will let know
the data direction (whether read or write) to microcontroller. Each PORT has its own
TRIS register E.g: For PORT A
TRISA=0 //making port as output port (write)
TRISA=1 //making port as input port (read)
We can also make specific bits of port as input or output.
TRISA.F2 = 1; // PORTA pin RA2 configured as input

2. PORT REGISTER:
It reads the levels on the pins of the deviceand it assigns logic values (0/1) to the
ports.The role of the PORT register is to receive the information from an external
source (like a sensor) or to send information to the external elements (like an LCD).
E.g:

3. LAT REGISTER:
The Data Latch register is also memory mapped. LAT register is associated with an
I/O pin. It eliminates the problems that could occur with read-modify-write instructions.

Latch Read:
A read of the LAT register returns the values held in the port output latches, instead of
the values on the I/O pins. A read-modify-write operation on the LAT register which is
associated with an I/O port, avoids the possibility of writing the input pin values into
the port latches.

Latch Write:
A write to the LAT register has the same effect as a write to the PORT register. A write
to the PORT register writes the data value to the port latch. Similarly, a write to the
LAT register writes the data value to the port latch.

PORT A:
PORTA is a 7-bit wide, bi-directional (I/O) port. The corresponding Data Direction
register is TRISA. This Port contains various features mentioned below:
 Port A pins are also multiplexed with analog inputs, i.e RA0, RA1, RA2, RA3,
RA5 have AN0, AN1, AN2, AN3, AN4 respectively.
 The RA4 pin is multiplexed with the Timer0 module clock input to become the
RA4/T0CKI pin. This pin is a Schmitt Trigger input and an open drain output.
 All other PORTA pins except RA4 have TTL input levels and full CMOS output
drivers.
 RA2 and RA3 are also multiplexed with the analog VREF- and VREF+ inputs
 RA5 also act as slave select input for synchronous serial port and can be used
as low voltages detect input.
 RA6 is used as OSC2 or clock pin.
The operation of each pin is selected by setting the control bits in the ADCON1
register.
Bit0
I/O AN0 TTL
RA0

Bit1
I/O AN1 TTL
RA1

Bit2
I/O AN2 TTL VREF-
RA2

Bit3
I/O AN3 TTL VREF+
RA3

Bit4
I/O T0CKI ST
RA4

Bit5
I/O AN4 TTL SS,LVDIN
RA5

Bit6
I/O TTL OSC2/CLK0
RA6

PORT B:
PORTB is an 8-bit wide, bi-directional port. The corresponding Data Direction
register is TRISB.
 AllPORTB pins have a weak internal pull-up. A single control bit (clearing bit
RBPU) can turn on all the pull-ups. For port pin as output, this weak pull-up is
automatically turned off. The pull-ups are disabled on a Power-on Reset.
 Four of the PORTB pins, RB7:RB4, have an interrupton-change feature. The
pins which are configured as inputs can only cause this interrupt to occur. This
interrupt can wake the device from SLEEP.
 RB0, RB1 and RB2 can be used as external interrupt inputs.
 RB3 can be used as the alternate peripheral pin for the CCP2 module.

Bit0 RB0 I/O TTL/ST INT0

Bit1 RB1 I/O TTL/ST INT1

Bit2 RB2 I/O TTL/ST INT2

Bit3 RB3 I/O TTL/ST CCP2

Interrupt on
Bit4 RB4 I/O TTL
change
Interrupt on ICSP
Bit5 RB5 I/O TTL/ST
change enable pin

Interrupt on Serial prog.


Bit6 RB6 I/O TTL/ST
change clock

Interrupt on Serial prog.


Bit7 RB7 I/O TTL/ST
change data

PORT C:
PORTC is an 8-bit wide, bi-directional port. The corresponding Data Direction register
is TRISC. PORTC is multiplexed with several peripheral functions:
 PORTC all pins have Schmitt Trigger input buffers.
 RC1 is configured as the default peripheral pin of the CCP2 module and RC2 for
CCP1.
 RC4 can also be the SPI Data In (SPI mode) or Data I/O (I2C mode).
 RC5 used for Synchronous Serial Port data output SDO
 RC6 is used as Addressable USART Asynchronous Transmit, or Addressable
USART Synchronous Clock.
 RC7 is used as Addressable USART Asynchronous Receive, or Addressable
USART Synchronous Data.

TMR1 oscillator
Bit0 RC0 I/O ST
output

TMR1 oscillator
Bit1 RC1 I/O ST CCP2
input

Bit2 RC2 I/O ST CCP1

Bit3 RC3 I/O ST

Bit4 RC4 I/O ST SDI/SDA

Bit5 RC5 I/O ST SDO

Bit6 RC6 I/O ST TX/CK

Bit7 RC7 I/O ST RX/DT

PORT D:
PORTD is an 8-bit wide, bidirectional port. The corresponding Data Direction register
is TRISD.
 PORTD all pins have Schmitt Trigger buffers when in I/O mode.
 It can be configured as a parallel slave port by setting control bit PSPMODE
(TRISE<4>). In this mode, the input buffers are TTL.

Bit0 RD0 I/O ST/TTL parallel slave port bit0

Bit1 RD1 I/O ST/TTL parallel slave port bit1

Bit2 RD2 I/O ST/TTL parallel slave port bit2

Bit3 RD3 I/O ST/TTL parallel slave port bit3

Bit4 RD4 I/O ST/TTL parallel slave port bit4

Bit5 RD5 I/O ST/TTL parallel slave port bit5

Bit6 RD6 I/O ST/TTL parallel slave port bit6

Bit7 RD7 I/O ST/TTL parallel slave port bit7

PORT E:
PORTE is a 3-bit wide, bi-directional port. The corresponding Data Direction register
is TRISE.
 These pins have Schmitt Trigger input buffers.
 They also control the parallel slave port operation.
 PORTE pins are multiplexed with analog inputs. When using them as
analog inputsthey must be configured as inputs.

Bit0 RE0 I/O AN5 ST/TTL RD parallel slave port bit0

Bit1 RE1 I/O AN6 ST/TTL WR parallel slave port bit1

Bit2 RE2 I/O AN7 ST/TTL CS parallel slave port bit2

I/O Bit manipulation Programming.


EXAMPLE: SIMULATIONS:WORKING:

PIC18F452 PORT B pins are configured as output and PORT D pins are configured
as input. We have used 4 push buttons. Crystal of 12MHz can be used. All LED are
firstly turned off.
Coding is done as:
 If 1st button is pressed then 1st LED will glow for one second and then turn off.
 If 2nd button pressed, 2nd LED will glow for one second and then turn off and so
on…

void main()
{
TRISD.F0 = 1; //Configure 1st bit of PORTD as input
TRISD.F1 = 1; //Configure 2nd bit of PORTD as input
TRISD.F2 = 1;
TRISD.F3 = 1;
TRISB.F0 = 0; //Configure 1st bit of PORTB as output
TRISB.F1 = 0; //Configure 2nd bit of PORTB as output
TRISB.F2 = 0;
TRISB.F3 = 0;

PORTB=0x00; //All LEDs OFF: 0x00 i.e. 00000000 All OFF


//All LEDs ON: 0xFF i.e. 0x 11111111 All ON
do
{
if(PORTD.F0 == 0) //If 1st switch is pressed
{
PORTB.F0 = 1; //1st LED ON
Delay_ms(1000); //1 Second Delay
PORTB.F0 = 0; //LED OFF
}

if(PORTD.F1 == 0) //If the 2nd switch is pressed


{
PORTB.F1 = 1; //2nd LED ON
Delay_ms(1000); //1 Second Delay
PORTB.F1 = 0; //LED OFF
}

if(PORTD.F2 == 0) //If the 3rd switch is pressed


{
PORTB.F2 = 1; //3rd LED ON
Delay_ms(1000); //1 Second Delay
PORTB.F2 = 0; //LED OFF
}

if(PORTD.F3 == 0) //If 4th switch is pressed


{
PORTB.F3 = 1; //4thLED ON
Delay_ms(1000); //1 Second Delay
PORTB.F3 = 0; //LED OFF
}
}while(1);
}
Timer/Counter:
A timer is a specialized type of clock which is used to measure time intervals. A timer
that counts from zero upwards for measuring time elapsed is often called
a stopwatch. It is a device that counts down from a specified time interval and used
to generate a time delay, for example, an hourglass is a timer.
A counter is a device that stores (and sometimes displays) the number of times a
particular event or process occurred, with respect to a clock signal. It is used to count
the events happening outside the microcontroller. In electronics, counters can be
implemented quite easily using register-type circuits such as a flip-flop.

Difference between a Timer and a Counter


The points that differentiate a timer from a counter are as follows −
Timer Counter
The register incremented for every The register is incremented considering 1 to
machine cycle. 0 transition at its corresponding to an
external input pin (T0, T1).
Maximum count rate is 1/12 of the Maximum count rate is 1/24 of the oscillator
oscillator frequency. frequency.
A timer uses the frequency of the A counter uses an external signal to
internal clock, and generates delay. count pulses.

instruction moves the value into the low-byte of Timer #0.


by running loops, but the timer/counter relieves the CPU from that redundant and
repetitive task, allowing it to allocate maximum processing time for other tasks.

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.

Timer Block Diagram

An oscillator is a circuit which produces a continuous, repeated, alternating waveform


without any input.

PIC Timer Module


PIC18F4520 has three independent timer which can be used as timer, Counters or
for PWM generation.
Below table provides the details of the three Timers. Same registers are used as
counter

Timer Size Control Count Min Max Delay


Register Register Delay

TIMER0 8-bit OPTION_REG TMR0 0.2usec 13.107ms

TIMER1 16-bit T1CON TMR1H,TMR1L 0.2usec 104.857ms

TIMER2 8-bit T2CON TMR2 0.2usec 819usec

Timer 0
The TMR0 module is an 8-bit timer/counter with the following features:

 8-bit timer/counter
 Readable and writable
 8-bit software programmable prescaler
 Internal or external clock select
 Interrupt on overflow from FFh to 00h
 Edge select for external clock

Timer0 Registers
The below table shows the registers associated with PIC18F4520 Timer0 module.

Register Description
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 Inetrrupt Enable flag(TMR0IE).

OPTION_REG
7 6 5 4 3 2 1 0
RBPU INTEDG T0CS T0SE PSA PS2 PS1 PS0

RBPU: NA for Timers

INTEDG: NA for Timers

T0CS: TMR0 Clock Source Select bit


1-Transition on T0CKI pin
0-Internal instruction cycle clock (CLKO)

T0SE: TMR0 Source Edge Select bit


1-Increment on high-to-low transition on T0CKI pin
0-Increment on low-to-high transition on T0CKI pin

PSA: Prescaler Assignment bit


1-Prescaler is assigned to the WDT
0-Prescaler is assigned to the Timer0

PS2:PS0: Prescaler Rate Select bits


 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.

Timer and Counter with PIC18F4550

Basically, a timer is a clock that controls an event sequence at a fixed amount


of time. Timers are used for the precise delay generation and also used to
trigger an activity before and after a predetermined time and to measure the
time elapsed between two successive events. Here in this chapter how to use
a timer and counter with PIC18F4550 is described in detail.

Timers in Microcontroller
The timer inside a microcontroller is a free running binary counter. The counter
increments for each pulse applied to it. The counter counts continuously from 0 to
(2^n)-1 where n is the number of bits. In PIC18F4550, there are 8-bit and 16-bit
timers. The timer takes the internal clock as a reference clock, while the counter
counts external clocks or pulses applied through port pins. So basically timer is a
counter with an internal clock.

The main advantage of timers and counters is that it works independent of


microcontroller CPU and the timer values can be read whenever needs. Basically, a
standard microcontroller consists of 1 or more hardware timer modules of different
bit lengths.

 8-bit timers- capable of counting 0-255


 16-bit timer – capable of counting 0-65535

The initial values of the timer register can be set by the user and can be used to
generate required counts.

Below is a functional diagram of a timer module.


Counters
Timers are also called counters because they are used to count external events.
Timers are mainly used for counting or measuring external events.

For example in the case of a visitor counter, the sensor placed for detecting the
presence of a person goes high when someone crosses the door. The output
of the sensor is connected to the Timer Clock Input Pin of the microcontroller.
The timer register inside the microcontroller increments each time when a
person crosses the door. The value can be later read by the CPU.

Prescalar
Prescalar is a configurable clock-divider circuit. It can be used to divide the clock
frequency input to the timer module. For example, if the instruction clock is
5MHz and we use a prescaler of 2 to divide it which effectively make the clock
2.5MHz. So each counting time will increase from 0.2 µs to 0.4 µs.

In PIC microcontroller, timer module provides 256, 128, 64, 32, 16, 8, 4, 2 and
1. 1 is actually prescaler bypassed.

Watchdog Timer
The watchdog timer can be used to force a restart of the microcontroller in the event
of a program crash.
Whenever software failed to clear the watchdog timer before its timeout period, the
watchdog timer resets the system. For this purpose, a watchdog timer is used to
overcome software failures in real-time applications. The watchdog timer is also used
to wake up the microcontroller from sleep mode.

In PIC18F-series microcontrollers family members the watchdog timer (WDT) is a free


running on-chip RC-based oscillator and does not require any external components.
When the WDT times out, a device RESET is generated. If the device is in SLEEP
mode, the WDT time-out will wake it up and continue with normal operation. The
watchdog is enabled/disabled by bit SWDTEN of register WDTCON. Setting SWDTEN
= 1 enables the WDT, and clearing this bit turns off the WDT. On the PIC18F452
microcontroller an 8-bit postscaler is used to multiply the basic time-out period from 1
to 128 in powers of 2. This postscaler is controlled from configuration register
CONFIG2H. The typical basic WDT time-out period is 18ms for a postscaler value of
1.

Time Delay calculation with Timer:


Timers as the name suggests pertain to time-related operations. They are mostly used
for exact delay generation. Timers are also used in various other operations like PWM
signal generation, auto-triggering of several other peripherals etc. The working and
configuration of PIC18F4550 Timers have been explained in this article.

Timers are the most essential peripheral for a microcontroller and every controller
provides a provision for using them. Beginners are advised to go through the tutorial
on Timers before going any further. For basic Timer operations, refer the Tutorial on
Timers. PIC18F4550 is equipped with four Timers namely, Timer0, Timer1, Timer2
and Timer3. Before going for the details of Timer configurations, it is important to learn
how time delay is calculated by the timer since exact delay generation is the most
common application of Timers.

Example: Time Delay calculation with Timer:

Given that a time delay of 1 sec is to be generated and a 12MHz crystal oscillator is
connected with PIC. Please note that this example considers external clock source for
the controller, however, PIC18F4550 has provision for both external as well as internal
clock source.

Timer is related to the internal frequency which is always Fosc/4.

Clock source frequency (Crystal)


Fosc = 12 MHz = 12000000 Hz

Therefore, Timer frequency :


FTimer = Fosc / 4 = 12000000 / 4 = 3000000 Hz = 3 MHz

If Prescaler = 1:256, then


FTimer = 3000000 / 256 = 11718.75 Hz

So, the time interval :


TTimer = 1 / FTimer = 1 / 11718.75 = 85 us (microseconds)

This means that when Timer runs, it will take 85 secs to increment its value at every
count.

To calculate the value to be filled in Timer rolling over register to generate 1 sec delay

No. of count for 1 sec Delay = 1sec / 85 us = 11718.75 = 2DC6H

So the value to be filled in Timer’s 16 bit register = FFFF – 2DC6 = D239


PIC18F4550 Microcontroller Timers and Registers
Each of the four Timers of PIC18F4550 has certain special features some of which
are explained below. The detailed list of these features can be obtained
from PIC18F4550 datasheet.

Timer0:
· Timer0 can work as Timer/Counter in both 8-bit and 16-bit modes
· Dedicated 8-bit, software programmable prescaler
· Selectable clock source (internal or external)
· Interrupt on overflow

Timer1:
· Timer1 can work as 16-bit timer or counter
· Readable and writable 8-bit registers (TMR1H and TMR1L)
· Selectable clock source (internal or external)
· Alternate clock source can be provided at Timer1 oscillator pins (T1OSO & T1OSI)
· Interrupt on overflow
· Timer1 can be multiplexed with other peripherals like ADC etc. and generates
special event triggering for CCP (Capture, Compare and PWM) events.

Timer2:
· 8-bit Timer and Period registers (TMR2 and PR2, respectively)
· Software programmable prescaler (1:1, 1:4 and 1:16)
· Software programmable postscaler (1:1 – 1:16)
· Interrupt on TMR2 to PR2 match
· Optional use as the shift clock for the MSSP (Master Synchronous Serial Port)
module

Timer3:
· Timer3 can work as 16-bit timer or counter
· Readable and writable 8-bit registers (TMR3H and TMR3L)
· Selectable clock source (internal or external)
· Alternate clock source can be provided at Timer1 oscillator pins (T1OSO & T1OSI)
· Interrupt on overflow
· Timer3 can be multiplexed with other peripherals like ADC etc. and generates
special event triggering for CCP (Capture, Compare and PWM) events.

These values are filled in the Timer register and it rolls over up to FFFF
Implementing Timer0 in PIC18F4550
Register Configuration
Register Description
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 Inetrrupt Enable flag(TMR0IE).

OPTION_REG
7 6 5 4 3 2 1 0
RBPU INTEDG T0CS T0SE PSA PS2 PS1 PS0

Every Timer has certain registers related to it which must be configured for desired
operations. The registers of Timer0 have been explained below.

1. T0CON (Timer0 Control Register)

Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0


TMR0ON T08BIT T0CS T0SE PSA T0PS2 T0PS1 T0PS0
Fig. 2: Bit Configuration of PIC18F4550 Timer0

T0PS2: T0PS0: These are prescaler selection bits. The bits setting is shown in the
following table to choose desired prescaler.

T0PS2:T0PS0 Prescale Value


000 1:256
001 1:128
010 1:64
011 1:32
100 1:16
101 1:8
110 1:4
111 1:2
Fig. 3: Bit Configuration of T0PS2: T0PS0 prescaler selection bits for configuring
Timer in PIC18F4550

PSA: This bit is set to high if there is no need to assign a prescaler value.
1 = Timer0 prescaler is not assigned. Timer0 clock input bypasses prescaler.
0 = Timer0 prescaler is assigned. Timer0 clock input comes from prescaler output.
T0SE: This bit is used when external source is selected for the Timer. This bit is used
to select external clock edge to increment the Timer.
1 = Increment on high-to-low transition on T0CKI pin (Pin6)
0 = Increment on low-to-high transition on T0CKI pin (Pin6)

T0CS: This bit is used to select the proper clock source for Timer0.
1 = Transition on T0CKI pin (Pin6)
0 = Internal instruction cycle clock (CLKO)

T08BIT: This bit selects the Timer mode.


1 = Timer0 is configured as an 8-bit timer/counter.
0 = Timer0 is configured as a 16-bit timer/counter.

TMR0ON: This bit is set to high (1) to enable the Timer0 and set to low (0) to stop it.

2. INTCON (Interrupt Control Register)

Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0


GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF
Fig. 4: Bit Configuration of Interrupt Control Register in PIC18F4550

TMR0IE: This bit is used to enable/disable the Timer0 overflow interrupt.


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

TMR0IF: This is Timer0 overflow flag bit. This bit is set when TMR0 register overflows.
This bit cleared by the software.

3. TMR0 (Timer0 Register)


This register is divided into registers TMR0H and TMR0L. Both registers are
accessible separately thus Timer0 can work in both 8-bit and 16-bit modes. In these
registers, pre-calculated value for delay is filled.

Using TOCON Bits


T0CONbits.T08BIT = 0; // 16-bit mode selected
T0CONbits.T0CS = 0; // Internal clock selected (timer mode ON)
T0CONbits.PSA = 1; // Prescalar NOT assigned
T0CONbits.TMR0ON = 1; // Turn ON the timer

Using Prescalar in Timer


For using prescaler, clear the PSA bit and assign the corresponding value in
T0PS2, T0PS1 and T0PS0 registers.
For example, to assign a prescaler of value 2

T0CONbits.T08BIT = 0; // 16-bit mode selected


T0CONbits.T0CS = 0; // Internal clock selected (timer mode ON)
T0CONbits.PSA = 0; // Prescalar assigned
T0CONbits.T0PS0 = 0; // Prescalar values
T0CONbits.T0PS1 = 0; // Prescalar values
T0CONbits.T0PS2 = 0; // Prescalar values
T0CONbits.TMR0ON = 1; // Turn ON the timer

Example Project
Objective:
To configure the Timer0 and generate 1 second delay.

Programming Steps:
1. Select the Prescaler, Clock option, Mode of Timer0 with the T0CON register.
2. Fill the higher byte of Timer value in TMR0H and then fill lower byte value in
TMR0L register.
3. Set the TMR0ON bit to start the timer.
4. Wait until the TMR0IF flag gets high.
5. As TMR0IF gets high, set it to zero and stop the timer by clearing the TMR0ON
bit.
6. To start the Timer0 again repeat the process from step2.

The time delay has been demonstrated by glowing a set of 8 LEDs one by one with
a delay of 1 sec which can be seen the adjoining video. The circuit diagram and code
for the same is also given.

Project Source Code


// Program to use Timer0 of PIC18F4550 Microcontroller

void T0_init();
void main()
{
TRISB=0; // COnfigure PortB as output Port.
LATB=0x01;
T0CON=0x07; // Prescaler= 1:256, 16-bit mode, Internal Clock
while(1)
{
T0_init(); // Initialize Timer0
LATB=(LATB<<1)|(LATB>>7); // Circular right shift at PortB
}
}

void T0_init()
{
TMR0H=0xD2; // Values calculated for 1 second delay with 12MHz
TMR0L=0x39;
T0CON.TMR0ON=1; // Timer0 On
while(INTCON.TMR0IF==0); // Wait until TMR0IF gets flagged
T0CON.TMR0ON=0; // Timer0 Off
INTCON.TMR0IF=0; // Clear Timer0 interrupt flag
}

Programmed and Interrupt Initiated I/O

Data transfer between the CPU and I/O devices can be done in variety of
modes. These are three possible modes:

1. Programmed I/O
2. Interrupt initiated I/O
3. Direct Memory Access (DMA)

The differences between programmed (Input/Output) I/O and interrupt-driven I/O are
as follows −

Programmed I/O
This I/O technique is the simplest to exchange data between external devices and
processors. In this technique, the processor or Central Processing Unit (CPU) runs or
executes a program giving direct control of I/O operations.
Processor issues a command to the I/O module and waits for the operation to
complete. Also, the processor keeps checking the I/O module status until it finds the
completion of the operation.
The processor's time is wasted, in case the processor is faster than the I/O module.
Its module is considered to be a slow module.
Its application is in certain low-end microcomputers. It has a single output and single
input instruction.
Each one of the instructions selects only one I/O device by number and transfers only
a single character by byte. Four registers are involved in this technique and they are
output status and character and input status and character.
Its disadvantage is busy waiting which means the processor consumes most of its time
in a tight loop by waiting for the I/O device to be ready to be used. Program checks or
polls an I/O hardware component, device, or item.
For Example − A computer mouse that is within a loop.
It is easy to understand. It is easy to program. It is slow and inefficient.
The system's performance is degraded, severely. It does not require initializing the
stack.
System's throughput is decreased due to the increase in the number of I/O devices
connected in the system. The best example is that of the PC device Advanced
Technology Attachment (ATA) interface using programmed I/O.

Interrupt-driven I/O
It is similar to the programmed-driven I/O technique. The processor does not wait until
the I/O operation is completed. The processor performs other tasks while the I/O
operation is being performed.
When the I/O operation is completed, the I/O module interrupts the processor letting
the processor know the operation is completed. Its module is faster than the
programmed I/O module.
The processor actually starts the I/O device and instructs it to generate and send an
interrupt signal when the operation is finished. This is achieved by setting an interrupt
enabled bit in the status register.
This technique requires an interrupt for each character that is written or read. It is an
expensive business to interrupt a running process as it requires saving context.
It requires additional hardware such as a Direct Memory Access (DMA) controller chip.
It is fast and efficient.
It becomes difficult to code, in case the programmer is using a low-level programming
language. It can get difficult to get the various pieces to be put to work well together.
This is done by the OS developer, for example, Microsoft or the hardware
manufacturer.
The system's performance is enhanced. It requires initializing the stack.
The system's throughput is not affected despite the number of I/O devices connected
in the system increasing as the throughput does not rely on the number.
For Example − The computer mouse triggers and sends a signal to the program for
processing the mouse event.
Interrupt-driven I/O is better as it is fast, efficient. The system's performance is
improved and enhanced.

Difference between Programmed and Interrupt Initiated I/O :

Programmed I/O Interrupt Initiated I/O


Data transfer is initiated by the means of
instructions stored in the computer program.
Whenever there is a request for I/O transfer theThe I/O transfer is initiated by the
instructions are executed from the program. interrupt command issued to the CPU.
There is no need for the CPU to stay
The CPU stays in the loop to know if the device in the loop as the interrupt command
is ready for transfer and has to continuously interrupts the CPU when the device is
monitor the peripheral device. ready for data transfer.
The CPU cycles are not wasted as
This leads to the wastage of CPU cycles as CPU continues with other work during
CPU remains busy needlessly and thus the this time and hence this method is
efficiency of system gets reduced. more efficient.
CPU can do any other work until it is
CPU cannot do any work until the transfer is interrupted by the command indicating
complete as it has to stay in the loop to the readiness of device for data
continuously monitor the peripheral device. transfer
Its module is faster than programmed
Its module is treated as a slow module. I/O module.
It can be tricky and complicated to
understand if one uses low level
It is quite easy to program and understand. language.
The performance of the system is severely The performance of the system is
degraded. enhanced to some extent.

Direct Memory Access

1. Direct Memory Access (DMA) means CPU grants I/O module authority to read
from or write to memory without involvement.
2. The previous ways of I/O suffer from two inherent drawbacks.
a) The I/O transfer rate is limited by the speed with which the processor can
test and service a device.
b) The processor is tied up in managing an I/O transfer; a number of instructions
must be executed for each I/O transfer.
3. When large volumes of data are to be moved, a more efficient technique is
required: Direct memory access. The DMA function can be performed by a
separate module on the system bus, or it can be incorporated into an I/O
module. In either case , the technique works as follow.
4. When the processor wishes to read or write a block of data, it issues a
command to the DMA module by sending the following information.
o Whether a read or write is requested.
o The address of the I/O devices.
o Starting location in memory to read from or write to.
o The number of words to be read or written.

5. The processor then continues with other work. It has delegated this I/O
operation to the DMA module, and that module will take care of it. The DMA
module transfers the entire block of data, one word at time, directly to or from
memory, without going through the processor. When the transfer is complete,
the DMA module sends an interrupt signal to the processor. Thus the processor
is involved only at the beginning and at the end of the transfer.
6. In programmed I/O CPU takes care of whether the device is ready or not. Data
may be lost. Whereas in Interrupt-driven I/O, device itself inform the CPU by
generating an interrupt signal. If the data rate of the I/O is too fast. Data may
be lost. In this case CPU most be cut off, since CPU is too slow for the particular
device. The initial state is too fast. It is meaningful to allow the device to put the
data directly to the memory. This is called DMA. DMA controller will take over
the task of CPU. CPU is general purpose but the DMA controller is specific
purpose.
7. A DMA module controls the exchange of data between main memory and an
I/O module. The processor sends a request for the transfer of a block of data
to the DMA module and is interrupted only after the entire block has been
transferred.

You might also like