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

Unit 3

This document discusses peripherals and interfacing in Unit III. It describes the I2C bus protocol which allows microcontrollers and other chips to communicate over a simple two-wire interface. The I2C bus uses an open-drain architecture with SDA for data and SCL for clock signals. Devices on the bus have unique addresses and can act as transmitters or receivers. The I2C protocol uses start, address, acknowledge, data, and stop conditions to facilitate communication between bus master and slave devices.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
73 views

Unit 3

This document discusses peripherals and interfacing in Unit III. It describes the I2C bus protocol which allows microcontrollers and other chips to communicate over a simple two-wire interface. The I2C bus uses an open-drain architecture with SDA for data and SCL for clock signals. Devices on the bus have unique addresses and can act as transmitters or receivers. The I2C protocol uses start, address, acknowledge, data, and stop conditions to facilitate communication between bus master and slave devices.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

UNIT III PERIPHERALS AND INTERFACING

UNIT III - PERIPHERALS AND INTERFACING


I2C Bus for Peripherals Chip Access– Bus operation-Bus subroutines– Serial
EEPROM—Analog to Digital Converter–UART-Baud rate selection–Data handling
circuit–Initialization -LCD and keyboard Interfacing -ADC, DAC, and Sensor
Interfacing.

Introduction:
Microprocessor based system design involves interfacing of the processor
with one or more peripheral device for the purpose of communication with
various input and output devices connected to it. During the early days of the
microprocessor revolution, these techniques required complex hardware
consisting of Medium scale integration devices, making the design highly
complex and time consuming. So, the manufacturers (INTEL) have developed a
large number of general and special purpose peripheral devices most of them
being single chip circuits. They are also programmable devices. Hence, these
peripheral devices are found to be of tremendous use to a system designer.
Peripheral devices, can broadly be classified into two categories.
(a) General purpose peripherals and
(b) Special purpose peripherals (Dedicated function peripherals)
General purpose peripherals are devices that perform a task, but may be
used for interfacing a variety of I/O devices to the microprocessor.
 Simple I/O -- (Non-programmable)
Programmable peripheral Interface (PPI) – (8255)
Programmable Interrupt Controller – (8259)
Programmable DMA Controller – (8237/8257)
Programmable Communication Interface – (8251)
Programmable Interval Timer – (8253/8254)
Special function peripherals or devices that may be used for interfacing a
microprocessor to a specific type of I/O device. These peripherals are more
complex and therefore, relatively more expensive than general purpose
peripherals. The special function peripherals (Dedicated function peripherals)
are
Programmable CRT Controller
Programmable Floppy Disc Controller
Programmable Hard Disc Controller
Programmable Keyboard and display interface.
The functioning of these devices varies depending on the type of I/O
device they are controlling.
I2C Bus for Peripherals:
In the early 1980's, NXP Semiconductors developed a simple bi-
directional 2-wire bus for efficient inter-IC control. This bus is called the Inter-
IC or I2C-bus. At present, NXP's IC range includes more than 150 CMOS and
bipolar I2C-bus compatible types of performing communication functions
between intelligent control devices (e.g. Microcontrollers), general-purpose
circuits (e.g. LCD drivers, remote I/O ports, memories) and application-
oriented circuits (e.g. Digital tuning and signal processing circuits for radio and

1
UNIT III PERIPHERALS AND INTERFACING

video systems). All I2C-bus compatible devices incorporate an on-chip interface


which allows them to communicate directly with each other via the I2C-bus.
This design concept solves the many interfacing problems encountered when
designing digital control circuits Today, the I2C bus is used in many other
application fields than just audio and video equipment. The bus is generally
accepted in the industry as a de-facto standard. The I2C bus has been adopted
by several leading chip manufacturers like Xicor, ST Microelectronics, Infineon
Technologies, Intel, Texas Instruments, Maxim, Atmel, Analog Devices and
others.
I2C Bus Protocol:
The I2C bus physically consists of 2 active wires and a ground
connection. The active wires, called SDA and SCL, are both bi-directional. SDA
is the Serial Data line, and SCL is the Serial Clock line. Every device hooked up
to the bus has its own unique address, no matter whether it is an MCU, LCD
driver, memory, or ASIC. Each of these chips can act as a receiver and/or
transmitter, depending on the functionality. Obviously, an LCD driver is only a
receiver, while a memory or I/O chip can be both transmitter and receiver.
The I2C bus is a multi-master bus. This means that more than one IC capable
of initiating a data transfer can be connected to it. The I2C protocol
specification states that the IC that initiates a data transfer on the bus is
considered the Bus Master. Consequently, at that time, all the other ICs are
regarded to be Bus Slaves.
As bus masters are generally microcontrollers, let's take a look at a general
'inter-IC chat' on the bus. Let's consider the following setup and assume the
MCU wants to send data to one of its slaves

First, the MCU will issue a START condition. This acts as an 'Attention'
signal to all of the connected devices. All ICs on the bus will listen to the bus
for incoming data. Then the MCU sends the ADDRESS of the device, it wants
to access, along with an indication whether the access is a Read or Write
operation had received the address, all IC's will compare it with their own
address. If it doesn't match, they simply wait until the bus is released by the
stop condition If the address matches, however, the chip will produce a
response called the ACKNOWLEDGE signal. Once the MCU receives the
acknowledge, it can start transmitting or receiving DATA. In our case, the MCU
will transmit data. When all is done, the MCU will issue the STOP condition.
This is a signal that the bus has been released and that the connected ICs may
expect another transmission to start any moment.

2
UNIT III PERIPHERALS AND INTERFACING

We have had several states on the bus in our example: START, ADDRESS,
ACKNOWLEDGE, DATA, STOP. These are all unique conditions on the bus.
Before we take a closer look at these bus conditions we need to understand a
bit about the physical structure and hardware of the bus.
As explained earlier, the bus physically consists of 2 active wires called SDA
(data) and SCL (clock), and a ground connection.
Both SDA and SCL are initially bi-directional. This means that in a particular
device, these lines can be driven by the IC itself or from an external device. In
order to achieve this functionality, these signals use open collector or open
drain outputs (depending on the technology).

The bus interface is built around an input buffer and an open drain or open
collector transistor. When the bus is IDLE, the bus lines are in the logic HIGH
state (note that external pull-up resistors are necessary for this which is easily
Forgotten). To put a signal on the bus, the chip drives its output transistor,
thus pulling the bus to a LOW level. The "pull-up resistor" in the devices as
seen in the figure is actually a small current source or even non-existent.
The nice thing about this concept is that it has a "built-in" bus mastering
technique. If the bus is "occupied" by a chip that is sending a 0, then all other
chips lose their right to access the bus. More will be explained about this in the
section about bus arbitration.
However, the open-collector technique has a drawback, too. If you have a long
bus, this will have a serious effect on the speed you can obtain. Long lines
present a capacitive load for the output drivers. Since the pull-up is passive,
you are facing an RC constant which will reflect on the shapes of the signals.
The higher this RC constant, the slower you can go. This is due to the effect
that it influences the slew rate of the edges on the I2C bus. At a certain point,
the ICs will not be able to distinguish clearly between a logic 1 and 0.

3
UNIT III PERIPHERALS AND INTERFACING

SDA (above) and SCL (below) with Rp = 10 kΩ and Cp = 300 pF. The SCL clock
runs with 100 kHz (nominal).

Bus Arbitration:
So far we have seen the operation of the bus from the master's point of view
and using only one master on the bus. The I2C bus was originally developed as
a multi-master bus. This means that more than one device initiating transfers
can be active in the system. When using only one master on the bus there is no
real risk of corrupted data, except if a slave device is malfunctioning or if there
is a fault condition involving the SDA / SCL bus lines. This situation changes
with 2 MCU's:

When MCU 1 issues a start condition and sends an address, all slaves will
listen (including MCU 2 which at that time is considered a slave as well). If the
address does not match the address of CPU 2, this device has to hold back any
activity until the bus becomes idle again after a stop condition.

As long as the two MCU's monitors what is going on on the bus (start and stop)
and as long as they are aware that a transaction is going on because the last
issued command was not a STOP, there is no problem.

Let's assume one of the MCU's missed the START condition and still thinks the
4
UNIT III PERIPHERALS AND INTERFACING

bus is idle, or it just came out of reset and wants to start talking on the bus
which could very well happen in a real-life scenario. This could lead to
problems. Since the bus structure is a wired AND (if one device pulls a line low
it stays low), you can test if the bus is idle or occupied.

When a master changes the state of a line to HIGH, it MUST always check that
the line really has gone to HIGH. If it stays low then this is an indication that
the bus is occupied and some other device is pulling the line low.

Therefore the general rule of thumb is: If a master can't get a certain line to go
high, it lost the arbitration and needs to back off and wait until a stop
condition is seen before making another attempt to start transmitting. The
rule says that a master loses arbitration when it cannot get either SCL or SDA
to go high when needed, this problem does not exist. It is the device that is
sending the '0' that rules the bus. One master cannot disturb the other
master's transmission because if it can't detect one of the lines to go higher, it
backs off, and if it is the other master that can't do so, it will behave the same.
This kind of back-off condition will only occur if the two levels transmitted by
the two masters are not the same. Therefore, let's have a look at the following
figure, where two MCUs start transmitting at the same time:

The two MCU's are accessing a slave in writing mode at address 1111001. The
slave acknowledges this. So far, both masters are under the impression that
they "own" the bus. Now MCU1 wants to transmit 01010101 to the slave,
while MCU 2 wants to transmit 01100110 to the slave. The moment the data
bits do not match anymore (because what the MCU sends is different than
what is present on the bus) one of them loses arbitration and backs off.
Obviously, this is the MCU which did not get its data on the bus. For as long as
there has been no STOP present on the bus, it won't touch the bus and leave
the SDA and SCL lines alone (yellow zone). The moment a STOP was detected,
MCU2 can attempt to transmit again.
Clock Synchronization:
All masters generate their own clock on the SCL line to transfer messages to
the I2C-bus. Data is only valid during the HIGH period of the clock. A defined
clock is therefore needed for the bit-by-bit arbitration procedure to take place.

Clock synchronization is performed using the wired-AND connection of I2C


interfaces to the SCL line. This means that a HIGH to LOW transition on the
SCL line will cause the devices concerned to start counting off their LOW period
and, once a device's clock has gone LOW, it will hold the SCL line in that state
until the clock HIGH state is reached. However, the LOW to HIGH transition of
5
UNIT III PERIPHERALS AND INTERFACING

this clock may not change the state of the SCL line if another clock is still
within its LOW period. The SCL line will therefore be held LOW by the device
with the longest LOW period. Devices with shorter LOW periods enter a HIGH
wait-state during this time.
Special Addresses and Exceptions:
In the I2C address, map there are so-called "reserved addresses". This section
contains some more details on these addresses and what they do. For
information about the Extended Addressing Mode, please refer to the
corresponding chapter.
Address R/W Designation

0000-000 0 General call address

0000-000 1 START byte (note

0000-001 x Reserved for the obsolete C-Bus format (note 3)

0000-010 x Reserved for a different bus format (note 4)

0000-011 x Reserved for future purposes (note 5)

0000-1xx x Reserved for future purposes

1111-1xx x Reserved for future purposes

1111-0xx x 10-bit slave addressing mode (note 6)


The general call address: This address is being used to access all devices on
the bus which are capable of handling the general call and need this data.
Devices which are capable of handling this general call, but do not need it will
not answer. All bytes transferred after this address may or may not be taken
by the slaves that are responding to it. If no slave is acknowledging a
transmitted byte, the operation is stopped by issuing a STOP on the bus. The
meaning of the general call address is specified in the 1st byte transmitted after
this "general call". This first byte can contain the following information: If the
LSB is set to 0:
Reset and write programmable part of slave address. All devices who
respond to this will reset and take in the programmable part of their
0000-
address. This is done by re-reading the levels on the address select
0110
pins of the device (if any). This command can be used to reset an
entire I2C system.

The same as above, but without the reset . This can be useful if the
0000-
state of the address select pins of a device is configurable. This way
0100
the device address will change.
If the LSB is set to 1:
6
UNIT III PERIPHERALS AND INTERFACING

This is a Hardware Call. If a device needs urgent attention from a


master device without knowing which master it needs to turn to, it can
use this call. This is a call "to whom it may concern". The device then
xxxx-
embeds its own address into the message. This call means as much
xxx1
as: Please contact me, I need to be serviced. All masters will listen and
the master that knows how to handle the device with the address
transmitted will contact its slave and act appropriately.
The START address:
This can be used between masters. A master which does not have an I2C
interface in hardware but in software needs to monitor the bus all the time.
Since this can require a lot of processing time, the START address was
introduced. The masters can sample the bus at a low rate. As soon as they
detect that the SDA line is low (it is held low for over 7 clock periods) it can
switch to a higher sampling rate to detect the Start condition. This address is
not followed by a stop condition, but rather by a repeated start condition.
Reserved for the obsolete C-Bus format: These addresses are used when
data other than I2C data have to be transmitted over the bus.
Reserved for future purposes: These addresses are for further expansion and
are currently not allowed.
10-bit slave addressing mode: Due to the increasing popularity of the I2C bus
the 7-bit address space got exhausted. This started posing problems for people
currently in the phase of designing a new I2C compatible IC. Therefore the I2C
standard has been updated to implement a 10-bit addressing mode.

A chip that conforms to the new standard receives two address bytes. The first
consists of the extended addressing reserved address, including the 2 MSB's of
the device address and the Read/Write bit. The second byte contains the 8
LSB's of the address. This scheme ensures that the 10 bit addressing mode
stays completely transparent for the other devices on the bus. Any new design
should implement this new addressing scheme.
Enhanced I2C (FAST Mode)
In the FAST mode, the physical bus parameters are not altered. The protocol,
bus levels, capacitive load etc. remain unchanged. However, the data rate has
been increased to 400 Kbit/s and a constraint has been set on the level of
noise that can be present in the system. To accomplish this task, a number of
changes have been made to the I2C bus timing.
High-speed I2C (HS-Mode)
High-speed mode (Hs-mode) devices offer a quantum leap in I2C-bus transfer
speeds. Hs-mode devices can transfer information at bit rates of up to 3.4
Mbit/s, yet they remain fully downward compatible with Fast- or Standard-
mode (F/S-mode) devices for bi-directional communication in a mixed-speed
bus system. With the exception that arbitration and clock synchronization is
not performed during the Hs-mode transfer, the same serial bus protocol and
data format is maintained as with the F/S-mode system. Depending on the
application, new devices may have a Fast or Hs-mode I2C-bus interface,
7
UNIT III PERIPHERALS AND INTERFACING

although Hs-mode devices are preferred as they can be designed-in to a greater


number of applications.
I2C Bus Events:
 Start and Stop Conditions
 Transmitting a Byte to a Slave Device
 Receiving a Byte From a Slave Device
 Getting Acknowledge from a Slave Device
 Giving Acknowledge to a Slave Device
 No Acknowledge ConditionS.3
Start and Stop Conditions:
Prior to any transaction on the bus, a START condition needs to be
issued on the bus. The start condition acts as a signal to all connected
IC's that something is about to be transmitted on the bus. As a result, all
connected chips will listen to the bus.
After a message has been completed, a STOP condition is sent. This is
the signal for all devices on the bus that the bus is available again (idle).
If a chip was accessed and has received data during the last transaction,
it will now process this information (if not already processed during the
reception of the message).
 The chip issuing the Start
condition first pulls the SDA
 Start
(data) line low, and next pulls
 the SCL (clock) line low.

 The Bus Master first releases the


 Stop
SCL and then the SDA line.

A few notes about start and stop conditions:
 A single message can contain multiple Start conditions. The use of this
so-called "repeated start" is common in I2C.
 A Stop condition ALWAYS denotes the END of a transmission. Even if it
is issued in the middle of a transaction or in the middle of a byte. It is
"good behavior" for a chip that, in this case, it disregards the information
sent and resumes the "listening state", waiting for a new start condition.
Transmitting a Byte to a Slave Device:
Once the start condition has been sent, a byte can be transmitted by the
MASTER to the SLAVE.

This first byte after a start condition will identify the slave on the bus (address)
and will select the mode of operation. The meaning of all following bytes
depends on the slave.

8
UNIT III PERIPHERALS AND INTERFACING

A number of addresses have been reserved for special purposes. One of these
addresses is reserved for the "Extended Addressing Mode". As the I2C bus
gained popularity, it was soon discovered that the number of available
addresses was too small. Therefore, one of the reserved addresses has been
allocated to a new task to switch to 10-bit addressing mode. If a standard slave
(not able to resolve extended addressing) receives this address, it won't do
anything (since it's not its address).

If there are slaves on the bus that can operate in the extended 10-bit
addressing mode, they will ALL respond to the ACK cycle issued by the master.
The second byte that gets transmitted by the master will then be taken in and
evaluated against their address.

Note: Even in 10-bit extended addressing mode, Bit 0 of the first byte after the
Start condition determines the slave access mode ('1' = read / '0' = write).

Receiving a Byte From a Slave Device:


Once the slave has been addressed and the slave has acknowledged this, a
byte can be received from the slave if the R/W bit in the address was set to
READ(set to '1').

The protocol syntax is the same as transmitting a byte to a slave, except that
now the master is not allowed to touch the SDA line. Prior to sending the 8
clock pulses needed to clock in a byte on the SCL line, the master releases the
SDA line. The slave will now take control of this line. The The line will then go
high if it wants to transmit a '1' or, if the slave wants to send a '0', remain low.

(1)All the master has to do is generate a rising edge on the SCL line
(2) read the level on SDA
(3) and generate a falling edge on the SCL line

9
UNIT III PERIPHERALS AND INTERFACING

(4). The slave will not change the data during the time that SCL is high.
(Otherwise a Start or Stop condition might inadvertently be generated.)

During (1) and (5), the slave may change the state of the SDA line.

In total, this sequence has to be performed 8 times to complete the data byte.
Bytes are always transmitted MSB first.

The meaning of all bytes being read depends on the slave. There is no such
thing as a "universal status register". You need to consult the data sheet of the
slave being addressed to know the meaning of each bit in any byte transmitted.
Getting Acknowledge from a Slave Device:
When an address or data byte has been transmitted onto the bus, then this
must be ACKNOWLEDGED by the slave(s). In case of an address: If the address
matches its own, then that slave and only that slave will respond to the
address with an ACK. In case of a byte transmitted to an already addressed
slave then that slave will respond with an ACK as well.

The slave that is going to give an ACK pulls the SDA line low immediately after
reception of the 8th bit transmitted, or, in case of an address byte, immediately
after evaluation of its address. In practical applications this will not be
noticeable.

This means that as soon as the master pulls SCL low to complete the
transmission of the bit
(1), SDA will be pulled low by the slave
(2). The master has now issued a clock pulse on the SCL line
(3). The slave will release the SDA line upon completion of this clock pulse
(4). The bus is now available again for the master to continue sending data or
to generate a stop condition.

In case of data being written to a slave, this cycle must be completed before
a stop condition can be generated. The slave will be blocking the bus (SDA kept
low by slave) until the master has generated a clock pulse on the SCL line.

10
UNIT III PERIPHERALS AND INTERFACING

Giving Acknowledge to a Slave Device:


Upon reception of a byte from a slave, the master must acknowledge this to
the slave device.The master is in full control of the SDA and the SCL line.

After transmission of the last bit of the master (1) the slave will release the SDA
line.

(1). The SDA line should then go high


(2).The Master will now pull the SDA line low
(3).Next, the master will put a clock pulse on the SCL line
(4). After completion of this clock pulse, the master will again release the SDA
line
(5).The slave will now regain control of the SDA line
Note: The above waveform is slightly exaggerated. You will not notice SDA is
gone, high in (2) and (5). A small spike might barely be visible.
Note: An Acknowledge of a byte received from a slave is always necessary,
EXCEPT on the last byte received If the master wants to stop receiving data
from the slave, it must be able to send a stop condition. Since the slave regains
control of the SDA line after the ACK cycle issued by the master, this could
lead to problems. Let's assume the next bit ready to be sent to the master is a
0. The SDA line would be pulled low by the slave immediately after the master
takes the SCL line low. The master now attempts to generate a Stop condition
on the bus. It releases the SCL line first and then tries to release the SDA line -
which is held low by the slave. Conclusion: No Stop condition has been
generated on the bus This condition is called a NACK: Not ACKnowledge. Do
not confuse this with No

ACKnowledge:
Condition Can Only Occur...

Not acknowledge (NACK) After a master has read a byte from a slave

No acknowledge After a master has written a byte to a slave

No Acknowledge Condition:
11
UNIT III PERIPHERALS AND INTERFACING

This is not exactly a condition. It is merely a state in the data flow between
master and slave. If, after transmission of the 8th bit from the master to the
slave, the slave does not pull the SDA line low, then this is considered a No
ACKcondition.

This means that either:


 The slave is not there (in case of an address)
 The slave missed a pulse and got out of sync with the SCL line of the
master.
 The bus is "stuck". One of the lines could be held low permanently.
In any case the master should abort by attempting to send a stop condition on
the bus.

A test for a "stuck bus" can be performed in the stop condition cycle.

I2C Bus Subroutine:

The SCL pin must have an open drain output while the SDA pin must be either
an input or have an open drain output, the I2C bus subroutine will repeatedly
access TRISC, the data direction register for PORTC. However, TRISC is located
at the bank 1 address, H’87’, which cannot be accessed by direct addressing
without first executing the instruction

Then changing the required bit of TRISC, and finally reverting back to Bank 0
with
Bcf STATUS,RP0
Instead of doing this, load the indirect pointer FSR, with the address of TRISC
and then do the required bit setting and bit clearing of TRISC bits indirectly.

12
UNIT III PERIPHERALS AND INTERFACING

Figure: 9.5 I2C typical message string format

For example , with the following definition


SCL equ 3
And
SDA equ 4
Then
Bsf INDF,SDA
Will relese the SDA line, letting the external pullup resistor of figuer9.1b pull it
high or some other I2C chip pull it low.
The use of FSR raise two condition
1. If these I2C subroutines are executed from the mainline program, then
any interrupt service routine that also uses FSR must set it aside upon
entry and restore it upon exit
2. Any use of indirect addressing to access a sequence of addresses in the
PIC’s RAM when used in conjunction with these I2C subroutines must
swap pointers in and out of FSR.
The timing requirements of figuer9.6 will be handled by inserting a number of
nop instructions between the instruction that change SDA and SCL. The
number of nop instruction required depends on the crystal clock rate. The
delay macro, define in figure 9.7a uses the equate of Freq to 4,10, or 20 to
insert a number of nop instruction equal tot the first,second, or third macro
parameters.

13
UNIT III PERIPHERALS AND INTERFACING

14
UNIT III PERIPHERALS AND INTERFACING

The equates and variables needed for the I2C subroutines are listed in Figuer
9.8 DEVADD is the selected peripheral chip’s 7-bit address on the I2C bus
shifted left one place to align it for use as a control byte. INTADD is a selected
registered memory address inside the selected peripheral chip by an I2C output
subroutine, I2Cout.DATAIN is the repository for the byte of data retrived by an
I2C input subroutine, I2Cin, from the selected register in the selkected
peripheral chip.

The I2Cout subroutine of figuer9.9 call a start subroutine to generate the


START condation, and calls a TX subroutine three times to send DEVADD(plus
R/W = 0), IINTADD, and DATAOUT out on the I2C bus. Finally, it calls a stop
subroutine to generate the STOP condition. The TX subroutine takes the byte
passed to it in W, uses a TXBUF variable to extract the bits one by one, and
transmits each bit using a BitOut subroutine. TX reads the acknowledge bit by
calling a BitIn subroutine, setting Z if ACK occurs.

The I2Cin subroutine of figure 9.9 is similar to the I2Cout subroutine. It calls
the Start subroutine and then the TX subroutine twice to send DEVADD (Plus
R/W = 0) and INTADD. Then it calls the Start subroutine to send (plus R/W =
1), the RX subroutine to read back a byte(with NOACK), and finally the Stop
subroutine.
noexpand
delay macro freq4, ferq 10, freq20
if freq==4
fill (nop), freq4
endif
if freq==10
fill (nop), freq10
endif

if freq==20
fill (nop), freq20
endif
endm
Figuer 9.7 (a) macro definition

0 nop for OSC = 4MHz (i.e., for freq eqn 4),


1 nop for OSC = 10MHz (i.e., for freq eqn 10),
2 nops for OSC = 20MHz (i.e., for freq eqn 20),

Figuer 9.7 (b) example of macro invoication which will insert

Freq eqn 4 ;set to 4,10,20, for 4MHz,10Mhz,20MHz


SDA eqn 4 ;I2C serial data bit of PORTC
SCL eqn 3 ;I2C serial clock bit of PORTC

15
UNIT III PERIPHERALS AND INTERFACING

Figuer: 9.8 I2C Equates

Cblock
.
.
.
DEVADD ;device I2C address X2
INTADD ;Internal address
DATAOUT ;Data to be written into INTADD during a writ
DATAIN ;Data to be read from INTADD during a read
TXBUF ;Buffer for each byte sent by TX
RXBUF ;Buffer for each byte received by RX
.
.
.
endc
Figuer: 9.8 I2C variables
;;;;;;;;;;I2C Subroutine;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;The I2Cout subroutine transfer out three bytes: DEVADD, INTADD and DATAOUT

I2Cout
Call start ; generate START condition
Movf DEVADD,W ;send peripheral address with R/W=0(write)
Call TX
Movf INTADD,W ;send the peripheral’s internal address
Call TX
Movf DATAOUT,W ;send data to write to peripheral
Call TX
Call STOP ; generate STOP condition
Return

; the I2Cin subroutine transfers out DEVADD(With R/W = 0) and INTADD,restarts,


;transfer out DEVADD(with R/W = 1) and reads one byte back into DATAIN

I2Cin
call START ;generat the START condition
movf DEVADD,W ;send peripheral address with R/W = 0
call TX
movf INTADD,W ;send peripherals internal address
call TX
call Restart ;Restart
movf DEVADD,W ;send peripheral address
iorlw B’00000001’ ; with R/W=1 (Read)
call TX
bsf TXBUFF,7 ;NOACK the following read of one byte
call RX ;Read byte
movf DATAIN ;into DATAIN
call STOP ;generate STOP condition
return

; the START subroutine initializes the I2C bus and then generate the START condition on the
;I2C bus
; the Restart entry point bypasses the initialization of the I2C bus

Start
16
UNIT III PERIPHERALS AND INTERFACING

Movlw B’00111011’ ;enable I2C master mode


Movwf SSPCON
Bcf PORTC,SDA ;drive SDA low when it is an output
Bcf PORTC,SCl ;drive SCL low when it is an output
Movlw TRISC ;set indirect pointer to TRISC
Movwf FSR
Restart
Bsf INDF,SDA ;make sure SDA is high
Bsf IINDF,SCL ;make sure SCL is high
Delay 0,1,2
Bcf INDF,SDA
Delay 0,1,2 ;t : START
Bcf INDF,SCL
Return

; the stop subroutine generate the stop condition on the I2C bus

Stop
Bcf INDF,SDA ;return SDA low
Bsf INDF,SCL ;drive SCL high
Delay 0,1,2 ;t : STOP
Bsf INDF,SDA ; and then drive SDA high
Return

; The TX subroutine sends the byte passed to it in W and returns Z=1 if ACK occurs & Z=0 if
NOACK occurs
TX
Movwf TXBUFF ;save parameter inTXBUFF
Bsf STATUS,C ;rotate a one through TXBUFF to count bits
TX_1
Rlf TXBUFF,F ;rotate TXBUFF left,through carry
Movf TXBUFF,F ;set Z bit when all eight bits have been transferred’
Btfss STATUS,Z ;until Z=1
Call Bitout ;send carry bit, then clear carry bit
Goto TX_1 ; then do it again
Call Bitin ; read acknowledge bit into bit 0 of RXBUFF
Movlw B’0000001 ; read acknowledge bit
Andwf RXBUFF,W ;Z=1 if ACK; Z=0 if NOACK
Return
; the RX subroutine recives a byte from the I2C bus into W, using RXBUFF buffer
; call RX with bit 7 of TXBUFF clear for ACK
;Call RX with bit 7 of RXBUFF set for NOACK

RX
Movlw B’00000001’ ; rotate a one through RXBUFF to the carry bit to count bits
Movwf RXBUFF
RX_1
Rlf RXBUFF,F ;shift previous bits left
Call Bitin ; read a bit fromSDA in to bit 0 of RXBUFF
Btfss STATUS,C ;C=1 yet
Got to RX_1 ; no do it again
Rlf TXBUFF,F ;move bit 7 of TXBUFF to carry bit
Call Bitout ; and from there to SDA as acknowledgement
Movf RXBUFF,W ;put received byte in to W
Return

17
UNIT III PERIPHERALS AND INTERFACING

; The Bitout subroutine transmit, then clears the carry bit

Bitout
Bdf INDF,SDA ;copy carry bit to SDA
Btfsc STATUS,C
Bsf INDF,SDA
Bsf INDF,SCL ;puls clock line
Delay 0,1,2
Bcf INDF,SCl
Bcf STATUS,C ;Clear carry bit
Return

; The Bitin subroutine recives one bit into bit0 of RXBUFF

bitin
bsf INDF,SDA ;release SDA line
Bsf INDF,SCL ;drive clock line high
Bcf RXBUFF,0 ;copy SDA to bit 0 of RXBUFF
Btfsc PORTC,SDA
Bsf INDF,SCl ;drive clock line low again
Return
;;;;;;;;;;;;;;;;;;; end of I2C subroutine;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

Figure: 9.9 I2C Subroutine

Serial EEPROM:
EEPROM technology supplies nonvolatile storage of variables to a PIC
controlled device or instruments. That is variables stored in an EEPROM will
remain there even after power has been turned off and then on again. Some
instruments use an EEPROM to store calibration data during manufacture. In
this way, each instrument is actually custom built, with customization that can
easily automate. Other instruments use an EEPROM to allow a user to store
several sets for setup information. For an instrument requiring a complicated
setup procedure, this permits a user to retrieve the setup for any one or
different measurements. Still other devices use an EEPROM in a way that is
transparent to a user, providing backup of setup parameters and thereby
bridging over power outages.

An EEPROM with I2C serial interface such as microchip technology’s 24LC01B


provides designer with a convenient solution to a need for nonvolatile data
storage. It holds 128bytes of data . it is package in a tiny eight-pin DIP or
surface-mount package. It requires only a+5V supply and will operate on the
“fast mode” (400 kbits/s) I2C bus. It draws less than 3 mA of supply current
during programming, 1 mA during reading, and 0.1 mA during sandby. It times
its own write cycle and automatically erases a byte before writing into it. A
block of upto 8 bytes can be written to the chip at one time and the chip will
program them all simultaneously in less than 10ms. The manufacture
guarantees successful writes for up to 10,000,000 erase/write cycles and data

18
UNIT III PERIPHERALS AND INTERFACING

retention beyond 200 years over an operating temperature range of 00C to


+700C or (-400C to +850C for industrial version)

The device with its interface circuit is illustrate in figure 9.15 the WP (write
protect) pin permits a manufacturer to program a part with calibration
constants ( with WP low) and then to permit only reads thereafter ( with WP
tied high).

The EEPROM makes use of an internal address pointer that is set during the
second byte of a “write” message string, as show in the figure 9.16a and 9.16b.
if further bytes are transmitted before the STOP condition, as in figure 9.16b,
they will accept as the data to be write into the selected internal address. The
reception of the STOP condition triggers the programming of these bytes into
the select addresses.
While the EEPROM is doing its autonomous programming operation, it will
acknowledge another write command. Because of this, the acknowledge bit can
be used as a flag to determine when the programming operation has been
completed. Simply send out the slave address with the write bit low and check
whether the ACK bit is pulled low by the EEPROM. Until it does get pulled low
in acknowledgment, the START condition followed by the same byte can be
sent repeatedly and the ACK bit tested. With a typical programming time of
2ms,, programming of many bytes can take place as rapidly as possible, faster
than simply allowing the 10ms worst-case write time to expire.

This EEPROM includes a page write buffer for writing upto 8bytes
simultaneously with the single write message string show in the figure 9.16b.
within 10ms after the STOP condition is received by the EEPROM, all of the
transmitted bytes will be programmed. However, all eight addresses are
constrained to have the same upper 5 bits. That is, only the lower 3 bits of
EEPROM internal address counter are incremented when more than one data
byte is included in a write command sequence. For example, if the EEPROM
address sent in the second byte of the write command is B’00010110’ and if
that address byte is followed by three data bytes and the STOP condition, then
the first of the three data bytes will be written into address B’00011000’. The
second into B’00010111’, and the third into B’00010000’

Reading any number of bytes of data from selected EEPROM address requires
that a starting address first be sent to EEPROM with the write message string
of figure 9.16a. this string is followed by the message string of figure 9.16c,
consisting of the START condition, a read command, and than a read of data
from consecutive address sent back by the EEPROM. The PIC signals the
EEPROM to send no further bytes by not pulling the SDA line low during the
last acknowledge but time. The sending of the STOP condition by the PIC
completes the message string.

19
UNIT III PERIPHERALS AND INTERFACING

The following bus protocol has been defined:

• Data transfer may be initiated only when the bus is not busy.
• During data transfer, the data line must remain stable whenever the clock
line is high. Changes in the data line while the clock line is high will be
interpreted as a Start or Stop condition.

 When the bus is not busy both the data and the clock line remains high
 For data transfers high-to-low transition of the SDA line while the clock
(SCL) is high determines a Start condition. All commands must be preceded
by a Start condition
 To stop the data transfer at low-to-high transition of the SDA line while the
clock(SCL) is high determines a Stop condition. All operations must be
ended with a Stop condition.

Each data transfer is initiated with a Start condition and terminated with a
Stop condition. The number of data bytes transferred between the Start and
Stop conditions is determined by the master device and is, theoretically,
unlimited (although only the last sixteen will be stored when doing a write
20
UNIT III PERIPHERALS AND INTERFACING

operation). When an overwrite does occur, it will replace data in a first-in,


first-out (FIFO) fashion.

Device Addressing
A control byte is the first byte received following the Start condition from
the master device. The control byte consists of a four-bit control code. For
the 24XX01, this is set as ‘1010’ binary for read and write operations. The
next three bits of the control byte are ‘don’t care for the 24XX01. The last bit
of the control byte defines the operation to
be performed. When set to ‘1’, a read operation is selected. When set to ‘0’,
a write operation is selected. Following the Start condition, the 24XX01
monitors the SDA bus checking the device type identifier being transmitted.
Upon receiving a ‘1010’ code, the slave device outputs an Acknowledge
signal on the SDA line. Depending on the state of the R/W bit, the 24XX01
will select a read or write operation.

Operation Control Code Block Select


R/W
Read 1010 Block Address 1
21
UNIT III PERIPHERALS AND INTERFACING

Write 1010 Block Address 0

WRITE OPERATION
Byte Write
Following the Start condition of the master, the device code (4 bits), the
block address (3 bits, don’t care) and the R/W bit, which is a logic low, is
placed onto the bus by the master transmitter. This indicates to the
addressed slave receiver that a byte with a word address will follow after it
has generated an Acknowledge bit during the ninth clock cycle. Therefore,
the next byte transmitted by the master is the word address and will be
written into the address pointer of the 24XX01.
Page Write
The write control byte, word address and first data byte are transmitted
to the 24XX01 in the same way as a byte write. However, instead of
generating a Stop condition, the master transmits up to 8 data bytes to the
24XX01, which are temporarily stored in the on- chip page buffer and will
be written into the memory once the master has transmitted a Stop
condition.

i2c bus connection to EEPROM


EEPROMs are designed to interface with Inter-Integrated Circuit (I2C) buses
and hardware. Fairchild’s electrically erasable programmable read only
memories (EEPROMs) offer valuable security features (write protection), two
write modes, three read modes and a wide variety of memory sizes.

22
UNIT III PERIPHERALS AND INTERFACING

Applications for the I2C bus and memories are included in SANs (small-area
networks), stereos, televisions, automobiles and other scaled-down systems
that don’t require tremendous speeds but instead cost efficiency and design
simplicity.

Connection of I2C bus with EEPROM and other Devices


The I2C bus configuration is an amalgam of microcontrollers and
peripheral controllers. By definition: a device that transmits signals onto the
I2C bus is the “transmitter” and a device that receives signals is the
“receiver”; a device that controls signal transfers on the line in addition to
controlling the clock frequency is the “master” and a device that is
controlled by the master is the “slave”. The master can transmit or receive
signals to or from a slave, respectively, or control signal transfers between
two slaves, where one is the transmitter and the other is the receiver. It is
possible to combine several masters, in addition to several slaves, onto an
I2C bus to form a Multimaster system. If more than one master
simultaneously tries to control the line, an arbitration procedure decides
which master gets priority. The maximum number of devices connected to
the bus is dictated by the maximum allowable capacitance on the lines, 400
pF, and the protocol’s addressing limit of 16k; typical device capacitance is
10 pF. Up to eight E2PROMs can be connected to an I2C bus, depending on
the size of the memory device implemented. The simplicity of the I2C system
is primarily due to the bidirectional 2- wire design, a serial data line (SDA)
and serial clock line (SKL), and to the protocol format. Because of the
efficient 2-wire configuration used by the I2C interface
START/STOP CONDITIONS
23
UNIT III PERIPHERALS AND INTERFACING

If both the data and clock lines are HIGH, the bus is not busy. To attain
control of the bus, a start condition is needed from a master; and to release
the lines, a stop condition is required.
Start Condition: HIGH-to-LOW transition of the data line while
the clock line is in a HIGH state.
Stop Condition: LOW-to-HIGH transition of the data line while the
clock line is in a HIGH state.
The master always generates the start and stop conditions. After the start
condition the bus is in the busy state. The bus becomes free after the stop
condition.

DATA BIT TRANSFER


After a start condition “S” one data bit is transferred during each clock
pulse. The data must be stable during the HIGH-period of the clock. The
data line can only change when the clock line is at a LOW level. Normally,
each data transfer is with 8 data bits and 1 acknowledged bit (byte format to
acknowledge).

ACKNOWLEDGE
Each data transfer needs to be acknowledged. The master generates the
acknowledge clock pulse. The transmitter releases the data line (SDA =
HIGH) during the acknowledge clock pulse. If there was no error detected,
the receiver will pull down the SDAline during the HIGH period of the
acknowledge clock pulse. If a slave receiver is not able to acknowledge, the
slave will keep the SDA line HIGH and the master can then generate a STOP
condition to abort the transfer. If a master receiver keeps the SDA line
HIGH, during the acknowledge clock pulse, the master signals the end of
data transmission and the slave transmitter release the data line to allow
the master to generate a STOP-condition.
FORMATS
There are three data transfer formats supported:
— Master transmitter writes to slave receiver; no direction change
— Master reads immediately after sending the address byte
— Combined format with multiple read or write transfers

ADDRESSING
The 7-bit address of an I2C device and the direction of the following data is
coded in the first byte after the start condition:

24
UNIT III PERIPHERALS AND INTERFACING

A “0” on the least significant bit indicates that the master will write
information to the selected Slave address device; a “1” indicates that the
master will read data from the slave.

SERIAL EEPROM APPLICATIONS

Serial EEPROMS are ideal non-volatile cost effective memory solutions in


applications that require:

 Small footprint and board space as in cellular phone applications


 BYTE level ERASE, WRITE, and READ of data
 Low voltage and current for handheld battery applications as in a keyless
entry transmitter
 Multiple non-volatile functions in the same application such as a VCR
 Low availability of microcontroller I/O lines

Market Common Applications


Consumer TV tuners, VCRs, CD players,
cameras, radios, and remote
controls

25
UNIT III PERIPHERALS AND INTERFACING

Automotive Airbags, anti-lock brakes,


odometers, radios, and keyless
entry
Office Automation Printers, copiers, PCs, and portable
PCs
Telecom Cellular, cordless and full features
Phones, faxes, modems, pagers,
and satellite receivers
Industrial Bar code readers, point-of-sale
terminals,
Smart cards, lock boxes,
Garage door openers, and test
measurement
Equipment

The typical functions that serial EEPROMs are utilized for being:
• Memory storage of channel selectors or analog controls (volume, tone, etc.) in
consumer electronics products
• Power down storage and retrieval of events such as fault detection or error
diagnostics in automotive products
• Electronic real time event or maintenance logs such as page counting in office
automation products. Also, configuration or DIP switch storage in office
automation products
• Last number redial storage and speed dial number storage in telecom
products
• User in-circuit reprogrammable look up tables such as bar code readers,
point-of-sale terminals, environmental controls and other industrial products

Temperature Sensor

The combination of an analog temperature transducer, an analog to digital


converter, and an I2C bus interface all in a tiny SO-8 surface mount
package represents a significant contribution to designers.

The analog voltage from the internal temperature passes to a converter


located in such close physical proximity that all of the potential problems of
noise and ground voltage offsets are handled inside the chip, once and for
all National semiconductor’s LM75 chip converts temperature over the range
of -250 to +1000C with ±20C accuracy. The same part delivers ±30C accuracy
for temperature down to -550C and up to ±1250C. for many applications an
even more important feature is its fine 0.50C resolution. Obtained with the
support of a 9 bit ADC. Figure 9.11 illustrate the two’s complement form of

26
UNIT III PERIPHERALS AND INTERFACING

the output. This 0.50C resolution means that small temperature difference
are measured with in 0.50C.

The LM75 chip also include thermal watchdog that can be set up interrupt
to the PIC on its RB0/INT edge triggered interrupt . when the temperature
rises past a programmable setpoint. TOS ( os stands fot over temperature
shut down) . it includes programmable hysteresis so that the temperature
must dip down below the setpoint TOS threshold to a lower THYST threshold
before rising again past the TOS setpoint to generate another output edge.

27
UNIT III PERIPHERALS AND INTERFACING

The chip includes a power on reset circuit that defaults to the operation
show in the figure 9.12b. at the power on time the PIC may come out of the
reset first; therefore, it is necessary to insert a delay before initializing the
LM75’s thermal watchdog circuitry. Otherwise the PIC’s commands to the
LM75 may go unnoticed
The register structure of the LM75 is show in the figure 9.13. when a “write”
message string is transmitted to the chip, the first byte select the chip for a
write and then the second byte loads the pointer register. The write message
string can stop there( illustrate in figure 9.14a), or it can continue with a 2-
byt write of 1000F = 75.50C to the TOS register (illustrate infiguer9.14b). once
the pointer has been set, any of these register can be read, reading 2 bytes

28
UNIT III PERIPHERALS AND INTERFACING

for temperature. TOS or THYST or reading just 1 byte for the configuration
registers.

If the thermal watchdog function of the LM75 is not use , then advantage
can be taken of the power-on default clearing of the pointer and
configuration register. In this case the interaction with the chip need be no
more than successive reads of the temperature. As in the figure 9.14C
The OS output operates in either of two modes, comparator or interrupt.
The host controls the temperature at which the alarm is asserted (TOS) and
the hysteresis temperature below which the alarm condition is not valid
(THYST). Also, the LM75’s TOS and THYST registers can be read by the
host. The address of the LM75 is set with three pins to allow multiple
devices to work on the same bus. Power-up is in comparator mode, with

29
UNIT III PERIPHERALS AND INTERFACING

defaults of TOS = +80°C and THYST = +75°C. The 3.0V to 5.5V supply
voltage range, low supply current, and I2C interface make the LM75 ideal
for many applications in thermal management and protection.

Applications
 Thermal System Management
 Thermal Protection
 Test Equipment, Computers and Office Electronics

Analog to digital converter:

An analog-to-digital converter (ADC) converts an analog signal into an


equivalent digital number. PIC 16C74A has an inbuilt ADC with the following
features

 8-bit conversion
 8 analog input channels
 An analog multiplexer
 A sample and hold circuit for signal on the selected input channel
 Alternative clock sources for carrying out conversion
 Adjustable sampling rate

30
UNIT III PERIPHERALS AND INTERFACING

 Choice of an internal or external reference voltage


 Interrupt to microcontroller on end of conversion

ADC Characteristic:

The PIC analog to digital converter has the idealized transfer funcation show in
the figure 10.1. it converts an input voltage to an 8 bit number. The input
voltage is scaled against a reference voltage,VRef

The reference voltage that is best suited for many application is the PIC supply
voltage VDD select as one option and connected to the ADC internally, there by
avoiding the need to dedicated a pin to this role. For a transducer whose
output is proportional to its own supply voltage and that uses the PIC supply
voltage as its own supply voltage, making VRef equal to VDD ia an ideal choice.
31
UNIT III PERIPHERALS AND INTERFACING

For other applications, using VDDas the refrence voltage offers the largest
possible analog voltage input range, since proper ADC operation requires

0V ≤ VInput ≤ VRef and also 3V ≤ VRef ≤ VDD

Given this choice of VRef = VDD the PIc parts ca assign up to eight pins to serve
as analog inputs to the ADC, using the pins and the register initializations
show in the figure 10.2 any pin that is assigned to serve as an analog and
digital input to the ADC can be read as a digital input by reading the
appropriate port pin or used as an analog input by selecting it as the input
channel to the ADC

32
UNIT III PERIPHERALS AND INTERFACING

The default power-on state of ADCON!(H’00’) powers down the digital I/O
circuitry for the five pins labeled “analog input or digital I/O”, there by making
them “analog input only” pins

For some applications, the use of an external voltage reference of 3.0V provides
the greatest possible resolution in the output.. this is particularly useful for
33
UNIT III PERIPHERALS AND INTERFACING

voltage difference measurement. Figure 10.3 illustrate the connection of an


external voltage reference to the PIC. The 10µF capacitor suppresses RF
switching transients.

The performance characteristic of the analog to digital converter are listed in


the figure 10.4 and expanded in figure 10.5. When a new input channel is
selected, the analog multiplexer sampling switch connects the input pin to
Chold, a sampling capacitor, show in the figure 10.5a. Vhold, the voltage on
reference must be allowed time to charge until it equals to Vsource to within one-
34
UNIT III PERIPHERALS AND INTERFACING

half of one of the voltage steps of figure 10.1. The larger resistance of the
source being measured, the longer this charging time will become. The
relationship is shown in figure 10.5b. A high source resistance can be
converted to a low source resistance with the help of the op amp “follower”
circuit of figure 10.5c.

After waiting out the sample time, a conversion can be initiated. The ADC
circuit will open the sampling switch and carry out the conversion of the input
voltage as it was at the moment the switch was opened. Upon completion of the
conversion, the sampling switch is closed and Vhold again tracks Vsource.

If the ADC is used to sample a single channel at equally spaced intervals, this
can be done automatically under interrupt control. The timer’s CCp module
can be used with Timer1 to initiate periodic ADC conversion of the select
channel. In addition, the ADC is set up to generate an interrupt when the
conversion has been completed. After this process has been setup and begun,
the CPU simply deals with each sample as it becomes available.

ADC USE:

Register ADCON1, TRISA, and TRISE must be initialized to select the refrence
voltage and the input channel desired, as described by figure 10.2 and 10.3.
then ADCON0 is initialized with the step listed in figure 10.6. the first step is
select the ADC clock source from among the four choices. The choice show in
the figure 10.6a provide the highest rate consistent with the constrain that the
ADC clock period must be 1.6µs or greater. The RC choice (made by setting

35
UNIT III PERIPHERALS AND INTERFACING

ADCON0[7:6] to 11) is designed for use with PIC being clocked by a relatively
slow clock. It lets the ADC run at a nominal 250kHz rate.

36
UNIT III PERIPHERALS AND INTERFACING

If just one analog input is to be used, it can be selected once and for all by
combining the channel selection of figuer10.6b with the ADC clock period
selection of figure 10.6a. if several analog channels are to be used, it is
important to remember to wait for the sample time discussed in conjunction
with figure 10.5. that is, select the channel, wait out the required sample time ,
and the initiate the conversion by setting the GO_DONE bit of ADCON0. When
GO_DONE =0 again, the result from ADRES(H’1E’), the ADC result register

37
UNIT III PERIPHERALS AND INTERFACING

If one or more channel channels are to be periodically sampled, the


timer1/CCP2 combination can be used to initiate each conversion. The register
involved as shown in the figure 10.7

38
UNIT III PERIPHERALS AND INTERFACING

39
UNIT III PERIPHERALS AND INTERFACING

UART( Universal Asynchronous Receiver & Transmitter):

UART stands for Universal Asynchronous Receiver / Transmitter, is a module


include in the following parts: PIC16C63, PIC16C65A, PIC16C73A, and
PIC16C74A,

It is a serial communication interface which uses two lines for sending (TX) and
receiving (RX) data. As its name indicates it is an
asynchronous communication interface, which means it doesn’t need to send
clock along with it as in synchronous communications. UART is the
communication standard of our old computer’s RS-232 serial port. Most of the
Microchip’s PIC Microcontrollers have built in USART Module. USART stands
for Universal Synchronous Asynchronous Receiver Transmitter. It can be
configured in the following Modes:

 UART – Asynchronous (Full Duplex)

 USRT Master – Synchronous (Half Duplex)

 USRT Slave – Synchronous (Half Duplex)

TXSTA – Transmit Status and Control Register:

 Bit 7 CSRC : Clock Source Select Bit, this bit has no application in the
Asynchronous mode operation of USART module. It is used to select
master or slave mode in Synchronous mode operation.

 Bit 6 TX9 : When this bit is set it enables the 9 bit transmission
otherwise 8 bit transmission is used. 9th bit in the 9 bit transmission
mode is commonly used as parity bit.

 Bit 5 TXEN : Setting this bit enables the transmission. In the


synchronous mode operation CREN and SREN bits of RCSTA register
overrides this bit.

40
UNIT III PERIPHERALS AND INTERFACING

 Bit 4 SYNC : This is the USART Mode select bit. Setting this bit selects
Synchronous mode while clearing this bit selects Asynchronous mode.

 Bit 3 Unimplemented : This bit is unimplemented and will read as 0.

 Bit 2 BRGH : This is the High Baud Rate Select bit for Asynchronous
mode operation and is unused in Synchronous mode. Setting this bit
selects High Speed and clearing this bit selects Low Speed baud rates.
You will can see the baud rate calculation later in this article.

 Bit 1 TRMT : This is the Transmit Shift Register (TSR) status bit. This
can be used to check whether the data written to transmit register is
transmitted or not. When the TRS is empty this bit is set and when the
TSR is full this bit will be 0.

 Bit 0 TX9D : This is the 9th bit of data in the 9 bit transmission mode.
This is commonly used as parity bit.

RCSTA – Receive Status and Control Register :

 Bit 7 SPEN : Serial Port Enable bit. Setting this bit enables serial port
and configures RC7, RC6 as serial port pins.

 Bit 6 RX9 : Setting this bit enables 9 bit reception otherwise it will be in
8 bit reception mode.

 Bit 5 SREN : Single Receive Enable bit. This bit has no effect on
Asynchronous mode and Synchronous Slave mode. Setting this bit will
enables Single Receive. This bit will cleared after the reception is
complete.

 Bit 4 CREN : Continuous Receive Enable bit. Setting this bit will enable
Continuous Receive. In the Synchronous Mode CREN overrides SREN.

 Bit 3 ADDEN : Address Detect Enable bit. This bit is applicable only in
Asynchronous 9 bit mode. Setting this bit enables Address Detect.

 Bit 2 FERR : Framing Error bit. 1 at this bit stands for Framing Error
while 0 stands for No Framing Error.

41
UNIT III PERIPHERALS AND INTERFACING

 Bit 1 OERR : Overrun Error bit. A high at this bit indicates that Overrun
error has occured.

 Bit 0 RX9D : This is the 9th bit of Received Data and is commonly used
as Parity Bit.

USART Baud Rate Generator (BRG)

Baud Rate Generator provides the required clock for the data transmission and
reception. USART module has a dedicated 8 bit baud rate generator which
supports both Synchronous and Asynchronous modes. The 8-
bit SPBRG register controls the time period of this free running timer. In
Asynchronous mode BRGH, 2nd bit of TXSTA register also controls the
generated baud rate but in Synchronous mode it is ignored. Baud Rate can be
calculated from the following equations, where FOSCis the clock frequency of the
microcontroller.

Waveform and BAUD-Rate Accuracy:

When a serial data is transmitted asynchronously, the data stream is


generated with the transmitter’s clock. The receiver must synchronize the
incoming data stream to the receiver’s clock.

42
UNIT III PERIPHERALS AND INTERFACING

An example of the transmission of 4 bytes is show in the figure 11.1. each 8 bit
is framed by a START bit and STOP bit. For transmission at 9,600Bd, each of
these bits lasts for a bit time(BT) of 1/9,600 second. Before the first frame is
transmitted, the line from the transmitter’s TX output to the recivers’S RX
input idles high. The receiver monitors its RX input, waiting for the line to drop
low because of the transmission of the (low) START bit. The receiver
synchronizes on this high to low transition. Then the receiver reads the 8 bit of
serial data by sampling the RX input at 1.5BT,2.5BT, 3.5BT, 4.5BT, 6.5BT,
7.5BT, AND 8.5BT as show in the figure 1101. It checks that the framing of
The byte has been interpreted correctly by reading the high STOP bit at 9.5BT.
if the RX line is actually low at this time , for whatever the reason, the receiver
sets a flag to indicate a framing error. Regardless of whether or not a framing
error occurs, the receiver then begins again, resynchronizing upon the next
high to low transition of the RX line. Because of this resynchronization, the
receiver can generate its own baud-rate clock that only approximate the
transmitter’s baud-rate clock and yet the reciver can recover the serial data
perfectly.

43
UNIT III PERIPHERALS AND INTERFACING

The PIC’s baud-rate clock operates at either of two ranges, called high
speedbaud rate and low speed baud rate. Using the low speed baud rate, the
reciver looks for STOP to START transition by sampling its RX input every
1/16th of one of its bit times, as show in the figure 11.2, then it counts six
more of these sample times to point where it reads a cluster of three closely
spaced samples of RX and votes among them to ensure that it is seeing the low
START bit. There after, it reads successive clusters of three samples spaced 16
sample time apart.in effect, the reciver is reading its input every 16 periods of
its sample clock.

BAUD-RATE Selection:

A desired baud rate can be approximated by the UART’s baud rate generator. If
the crystal clock rate were selected to be carefully chosen multiple pf the
desired baud rate, then the baud rate generator would produce the desired
baud rate exactly. The clock rates used by microchip to characterized the three
speed grades of their parts

4MHz 10MHz 20MHz

44
UNIT III PERIPHERALS AND INTERFACING

These speed grades do not provide exact multiples of the popular 9,600Bd and
19,200Bd rate commonly used by personal computer serial port. However, the
flexibility of the baud rate generator circuitry permits close approximation to
both 9,600 Bd and 19,200Bd with any of the standard clock rates. The baud
rate is derived from the crystal rate using an 8 bit presentable divider and a
fixed diver of either 16 or 64, as show in the figure 11.4b. the results are
tabulated in the figure 11.4a. even in the worst case , the percent error of the
approximate baud rate is only one-third of the percent error that cannot be
tolerated by the UART.

Nominal OSC =4MHz OSC = 10MHz OSC = 20MHz


Baud Rate BRGH SPBRG %error BRGH SPBRG %error BRGH SPBRG %error
9,600 baud 1 25 +0.16% 1 64 +0.16% 1 129 +0.16%
19,200 baud 1 12 +0.16% 1 32 -1.4% 1 64 +0.16%

Figure: 114.a Register contents and accuracy of approximated baud rate

For BRGH = 1(high speed baud rate)

For BRGH =0 (low speed baud rate)

Figure: 114.b Relation between OSC,BRGH, SPBRG, and Bayd Rate

UART Data Handling Circuitry:

The transmitted data circuit show in the figure 11.5a. to transmit a byte of
data serially from TX pin, the byte written to TXREG register. Assuming there
is not already data in TSR (transmit shift register), the content of TXREG will
be automatically transferred to the TSR, making TXREG available for a second
byte even as the first byte is being shifted out of the TX pin, framed by START
and STOP bits

45
UNIT III PERIPHERALS AND INTERFACING

46
UNIT III PERIPHERALS AND INTERFACING

The receiver data circuit is similar, with received data shifted into RSR(receiver
shift register) when it is in place, the STOP bit is checked and an error flag is
set if the STOP bit does not equal one. In any case, the receiver byte is
automatically transferred into a 2 byte FIFO. If the FIFO was initially empty,
the receiver byte will fall through to the RCREG (receiver register) virtually
immediately, where it is ready to be read by the CPU. If the CPU is slow in
reading the RCREG, a second byte can be received at the RX pin. When it is in
place in the RSR, it will follow the first byte into the 2 byte FIFO. At that point,
the FIFO is full. If the third byte enters the RX pin and is shifted all the way
across the RSR before at least one of the two bytes in the FIFO has been read,
then the new byte will be lost. An overflow error flag will be set, alerting the
receiver software of the loss of a byte of data

At 9600Bd, it takes 10/9600 second, or just a little longer than a millisecond,


to receive each byte. If the receiver bytes are handled under interrupt control,
each byte should be easily handled in a timely fashion, well before an overrun
error can even occur. No oher interrupt handler should be permitted to lock
out.

UART Initialization:

The register involved with UART is show in the figure 11.6. the data direction
bit associated with the RC6/TX pin and the RC7/RX pin must both be set up
as inputs, with ones in bits 6 and 7 of the TRISC register, the setting of these
two bits disable the general I/O port output circuitry associated with these two
pins( the handling of these bits of TRISC stands in contrast to the clearing of
bits 3 and 5 of TRISC in support of the serial peripheral interface output pins)

The UART’s baud rate and its transmit and receive funcations are initialized by
writes to SPBRG, TXSTA, and RCSTA, as show in figures 11.4 and 11.6 at 9600
Bd, each transfer takes about a millisecond, so sending or receiving a string of
characters is best carried out under interrupt control. The flag and interrupt
enable bits of the PIR1,PIE1 and INTCOON register control the timing of CPU
interactions with the UART.

UART Use:

A major application for the PIC’s UART is to provide a two-wire(plus ground)


serial interface to a personal computer. The circuit of figure 11.7 uses
mortorola chip to translate between the ov to a =5V logic level signal swings on
the PIC’s RX and TX pins and ±10V signal swings that support the RS-232

47
UNIT III PERIPHERALS AND INTERFACING

interface requirement. Both the PIC and the PC should be setup for the same
baud rate and for one start bit, 8data bits, one stop bit, and no parity bit

48
UNIT III PERIPHERALS AND INTERFACING

49
UNIT III PERIPHERALS AND INTERFACING

Given this setup, the PIC will respond to PCIF interrupts by reading each byte
from the RCREG register sent by the PC. The RCIF flag will clear itself when the
byte read from RCREG leaves the receive circuit’s FIFO empty.

The PIC sends out a string of bytes by writing them, one by one under
interrupt control, to TXREG , the TXIF flag takes care of itself, clearing
automatically when TXREG is written to, and setting again as the data written
TXREG are automatically transferred to the transmit shift register, at the
completion of sending the string of bytes to the PC, the TXIE bit in the PIE1
register is cleared to disable further ”transmit” interrupts until another string
needs to be sent to the PC

50
UNIT III PERIPHERALS AND INTERFACING

Another application of the PIC UART is to couple two PIC’s together. In this way
some of the work that would be done by one PIC is off loaded to a second PIC,
figure 11.8 show s this connection of two PIC’s, using the maximum possible
baud rate to obtain fast coupling between the two PICs with in 40 internal
clock cycles, what is written into one PIC’s TXREG register appears in the
other PIC’s RCREG register.

Carrying out transfers at this fast rate calls for some precautions is need if
overrun error are to avoided, given PICs that are try to carry out the task in
additional to monitoring the UART’s RCREG register. A given PIC can only
receive 2 bytes into its FIFO without reading them immediately. Any further
bytes received will be discard until the earlier bytes are read out of the FIFO,
making room for new bytes

51
UNIT III PERIPHERALS AND INTERFACING

Keypad:
A keypad is a matrix of push-buttons aligned in rows and columns to provide
user input, a 3x4 keypad is basically formed like the following schematic:

it consists of 3 columns and 4 rows, hence the name, whenever the user taps
one button, the column and the row corresponding to that button are shorted,
for example, if a user chooses to tap the "5" button, col2 and row2 are shorted,
if a users picks "0" button, col2 and row4 are shorted, and so on. the method
used to read such input is called Scanning, you connect the rows and the
columns to the microcontroller, you set the columns as outputs, rows as
inputs (or vice versa) and you start feeding a pattern of inputs to the columns
while checking the readings of the rows.

For example, if you tied all rows through pull-up resistors to Vcc, all row
inputs are typically 1s (1111), now if you start feeding columns with the
following pattern, 011, 101, 110, you can check which row conducts the 0
signal to the controller, thus, you'll detect the shorted row and column.
example: if a user presses button "6", when I feed the columns by 011, the
rows output would be 1111, when I feed it by 101, the rows output would be
also 1111, but when I feed it by 110, button "6" will conduct the 0 signal, thus
my rows output would be 1011, Knowing that I used col3 to conduct the 0
signal, and I got the 0 signal at row2, I'll know the pressed button is "6".

Using PIC-C to Read a Keypad:

52
UNIT III PERIPHERALS AND INTERFACING

PIC-C provides a common library for reading keypads named kbd.c, all you
have to do is to include the kbd.c library in your code, and use the function
kbd_getc() to scan the keypad.
kbd.c library uses either port D or port B to interface the keypad, you'll find the
schematic for the interface further below, but if you need to use other ports to
interface your keypad, you'll have to use a user defined library, you can find
those on ccsinfo.com forum, or you can write your own library (which is pretty
simple).

Note: the kbd_getc(); function returns the ASCII code of the pressed button
(returns a character).

The Alphanumeric LCD:


An alphanumeric LCD is a type of LCDs that only displays English letters,
numbers and some ASCII characters, those LCDs contains a controller unit
that processes the input and forms the displayed character on the LCD, most
alphanumeric LCDs have a parallel interface, some other LCDs have a serial
interface to minimize the construction complicity.
Alphanumeric LCDs comes in different sizes, the size describes the number of
characters an LCD can display, common sizes are 16x2, 20x2, 16x4, 20x4
..etc. a 16x2 has 2 rows and can display 16 characters on each row.

Parallel LCD Pinout:


Parallel LCDs typically have 16 pins as following:
- Power Supply Pins:
Vss : Ground reference (0V)
Vcc : +5V supply voltage
Vee : Contrast pin, typically connected to GND via a resistor (0Ω - 5kΩ),
change the value to change the contrast.
- Control Bus Pins:
RS : Register Select, used to set the LCD either to command mode or to data
mode.
R/W : Read/Write select, used either to read characters from LCD or to write
new characters.
E : Active low Enable signal.
- Data Bus Pins:

53
UNIT III PERIPHERALS AND INTERFACING

D0-D7 : used to pass 8Bit character data, you have the choice either to use
only 4Bit bus (D4-D7) or to use the whole data bus.
- Backlight Voltage Pins:
A : Anode (+5V)
K : Cathode (0V)
used to turn ON/OFF the backlight LED of your LCD.

Using PIC-C to Write to LCD:


To write to an LCD you need a software library, you can either go with the
original lcd.c library that comes with your compiler's software bundle (which I
don't recommend), or you can use flex_lcd.c libraries written by PCM
programmer, here:
The flex_lcd.c library gives you the opportunity to select PIC pins to be
connected to the LCD by changing the definers at the top of the library.

After including the flex_lcd.c library in your code, you should initialize the LCD
at the beginning of your main code using the function lcd_init();
Then you can use the function lcd_putc("Your String"); to display your
strings.

The Schematic:

Click on the schematic to zoom in,


I've selected the LCD pinouts in flex_lcd as following:

#define LCD_DB4 PIN_B4


#define LCD_DB5 PIN_B5
#define LCD_DB6 PIN_B6
54
UNIT III PERIPHERALS AND INTERFACING

#define LCD_DB7 PIN_B7

#define LCD_E PIN_B3


#define LCD_RS PIN_B1
#define LCD_RW PIN_B2

and commented out


// #define USE_LCD_RW 1

The PIC-C Code:

/*
PIC16F877A interface to 3x4 Keypad and 16x2 LCD

Badr Ghatasheh
[email protected]
*/

#include <16f877a.h>
#fuses XT,NOLVP,NOWDT,NOPROTECT
#use delay(clock=4000000)
#include "flex_lcd.c"
#include <kbd.c>

void main()
{
char k=0; // Character k to store keypad input
delay_ms(1);
/* Peripherals Configurations */
lcd_init(); // Turn LCD ON, along with other initialization
commands
kbd_init(); // Initialize Keypad

lcd_gotoxy(1,1); // point LCD cursor to col1 row1


lcd_putc("Hello World !!"); // print on LCD
lcd_gotoxy(1,2); // point LCD cursor to col1 row2

while(1) // infinite loop


{
k = kbd_getc(); // read keypad input (if exists)
if(k!=0) // if key captured
{
lcd_putc(k); // print captured key to lcd
k=0; // reset k for another loop round
delay_ms(250); // delay between key presses
55
UNIT III PERIPHERALS AND INTERFACING

}
delay_ms(1); // delay_between read trials
}
}

56

You might also like