Unit II
Unit II
Unit II
I/O Port : I/O Port structure with programming: I/O Port structure, I/O Port
programming, I/O Bit manipulation Programming.
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
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.
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.
Interrupt on
Bit4 RB4 I/O TTL
change
Interrupt on ICSP
Bit5 RB5 I/O TTL/ST
change enable pin
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
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.
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.
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;
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 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
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 initial values of the timer register can be set by the user and can be used to
generate required counts.
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.
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.
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.
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
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.
T0PS2: T0PS0: These are prescaler selection bits. The bits setting is shown in the
following table to choose desired prescaler.
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)
TMR0ON: This bit is set to high (1) to enable the Timer0 and set to low (0) to stop it.
TMR0IF: This is Timer0 overflow flag bit. This bit is set when TMR0 register overflows.
This bit cleared by the software.
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.
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
}
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.
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.