Unit 3
Unit 3
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
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.
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
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
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
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).
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
After transmission of the last bit of the master (1) the slave will release the SDA
line.
ACKnowledge:
Condition Can Only Occur...
Not acknowledge (NACK) After a master has read a byte from 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.
A test for a "stuck bus" can be performed in the stop condition cycle.
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
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 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
15
UNIT III PERIPHERALS AND INTERFACING
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
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
; 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
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
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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
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.
18
UNIT III PERIPHERALS AND INTERFACING
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
• 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
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.
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.
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.
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.
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.
25
UNIT III PERIPHERALS AND INTERFACING
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
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
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
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
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
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
38
UNIT III PERIPHERALS AND INTERFACING
39
UNIT III PERIPHERALS AND INTERFACING
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:
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.
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 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.
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.
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.
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
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.
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
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:
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".
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).
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.
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:
/*
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
}
delay_ms(1); // delay_between read trials
}
}
56