You are on page 1of 44

Serial Port Programming interfacing with 18FXXXX

The communication is very well known terminology which involves the exchange of
information between two or more mediums. In embedded systems, the communication means the
exchange of data between two microcontrollers in the form of bits. This exchange of data bits in
microcontroller is done by some set of defined rules known as communication protocols. Now
if the data is sent in series i.e. one after the other then the communication protocol is known
as Serial Communication Protocol. More specifically, the data bits are transmitted one at a
time in sequential manner over the data bus or communication channel in Serial Communication.

Types of Communication Protocols


There are different types of data transfer available in the digital electronics such as serial
communication and parallel communication. Similarly the protocols are divided into two types
such as Serial Communication Protocol and Parallel Communication Protocols. Examples
of Parallel Communication Protocols are ISA, ATA, SCSI, PCI and IEEE-488. Similarly there
are several examples of Serial Communication Protocols such as CAN, ETHERNET, I2C,
SPI, RS232, USB, 1-Wire, and SATA etc.
In this article, the different types of Serial Communication Protocols will be discussed. Serial
communication is the most widely used approach to transfer information between data
processing peripherals. Every electronics device whether it is Personal Computer (PC) or Mobile
runs on serial communication. The protocol is the secure and reliable form of communication
having a set of rules addressed by the source host (sender) and destination host (receiver) similar
to parallel communication.

Transmission Modes in Serial Communication


As already said above that in serial communication data is sent in the form of bits i.e. binary
pulses and it is well known that, binary one represents the logic HIGH and zero represents the
logic LOW. There are several types of serial communication depending on the type of
transmission mode and data transfer. The transmission modes are classified as Simplex, Half
Duplex and Full Duplex.

Simplex Method:

In simplex method either of the medium i.e sender or receiver can be active at a time. So if the
sender is transmitting the data then receiver can only accept and vice versa. So simplex method
is one-way communication technique. The well-known examples of simplex method are
Television and Radio.

Half Duplex Method:

In half duplex method both sender and receiver can be active but not at the same time. So if the
sender is transmitting then receiver can accept but cannot send and similarly vice versa. The
well-known examples of the half duplex is the internet where the user sends a request for a data
and the gets it from server.

Full Duplex Method:

In full duplex method, both receiver and transmitter can send data to each other at the same time.
The well-known example is mobile phone.

Clock Synchronization
The clock is different for serial devices and it is classified in two type viz. Synchronous Serial
Interface and Asynchronous Serial Interface.

Synchronous Serial Interface:

It is a point-to-point connection from a master to slave. In this type of interface, all the devices
use single CPU bus to share data and clock. The data transmission becomes faster with same bus
to share clock and data. Also there is no mismatch in baud rate in this interface. In transmitter
side, there is a shift of the data onto serial line providing the clock as a separate signal as there is
no start, stop and parity bits are added to data. In receiver side, the data is being extract using the
clock provided by the transmitter and converts the serial data back to the parallel form. The well-
known examples are I2C and SPI.

Asynchronous Serial Interface:

In asynchronous Serial Interface, the external clock signal is absent. The Asynchronous Serial
Interfaces can be seen in mostly in long distance applications and are a perfect fit for the stable
communication. In asynchronous Serial Interface the absence of external Clock Source makes it
rely on several parameters such as Data Flow Control, Error Control, Baud Rate Control,
Transmission Control and Reception Control. On the transmitter side, there is a shifting of
parallel data onto the serial line using its own clock. Also it adds the start, stop and parity check
bits. On the receiver side, the receiver extracts the data using its own clock and convert the serial
data back to the parallel form after stripping off the start, stop, and parity bits. The well-known
examples are RS-232, RS-422 and RS-485.

Other Terms Related to Serial Communication


Apart from Clock Synchronization there are certain things to remember when transferring data
serially such as Baud Rate, Data bit selection (Framing), Synchronisation and error checking.
Let‟s discuss these terms in brief.

Baud Rate: Baud rate is rate at which the data is transferred between the transmitter and receiver
in the form of bits per second (bps). The most commonly used baud rate is 9600. But there are
other selection of baud rate such as 1200, 2400, 4800, 57600, 115200. The more the baud rate
will be fats the data will be transferred at a time. Also for the data communication the baud rate
has to be same for both transmitter and receiver.

Framing: Framing is referred to the number of data bits to be sent from transmitter to receiver.
The number of data bits differs in case of application. Most of the application uses 8 bits as the
standard data bits but it can be selected as 5, 6 or 7 bits also.

Synchronization: Synchronization Bits are important to select a chunk of data. It tells the start
and end of the data bits. The transmitter will set start and stop bits to the data frame and the
receiver will identify it accordingly and do the further processing.

Error Control: The error control plays an important role while serial communication as there
are many factors which affects and adds the noise in the serial communication. To get rid of this
error the parity bits are used where parity will check for even and odd parity. So if the data frame
contains the even number of 1‟s then it is known as even parity and the parity bit in the register is
set to 1. Similarly if the data frame contains odd number of 1‟s then it is known as odd parity and
clears the odd parity bit in the register.

Protocol is just like a common language that system uses to understand the data. As described
above, the serial communication protocol is divided into types i.e. Synchronous and
Asynchronous. Now the both will be discuss in detail.
Synchronous Serial Protocols
The synchronous type of serial protocols such as SPI, I2C, CAN and LIN are used in
different projects because it is one of the best resources for onboard peripherals. Also these are
the widely used protocols in major applications.

USB

USB (Universal Serial Bus) is widely protocol with different versions and speeds. A maximum
of 127 peripherals can be connected to a single USB host controller. USB acts as "plug and play"
device. The USB are used in almost devices such as keyboards, printers, media devices, cameras,
scanners and mouse. It is designed for easy installation, faster data rated, less cabling and hot
swapping. It has replaced the bulkier and slower serial and parallel ports. USB uses differential
signalling to reduce interference and allow high-speed transmission over a long distance.

A differential bus is built with two wire, one of represents the transmitted data and the other its
complement. The idea is that the 'average' voltage on the wires does not carry any information,
resulting in less interference. In USB, the devices are allowed to draw a certain amount of power
without asking the host. USB uses only two wires to for data transfer and are faster than the
serial and parallel interface. USB versions supports different speeds such as 1.5Mbps (USB
v1.0), 480 Mbps (USB2.0), 5Gbps (USB v3.0). Length of individual USB cable can reach up to
5 meters without a hub and 40 meters with hub.

CAN

The Controller Area Network (CAN) is used in e.g. automotive to allow communication between
ECUs (Engine Control Units) and sensors. The CAN protocol is robust, low-cost and message
based and covers in many applications - e.g. cars, trucks, tractors, industrial robots. The CAN
bus system allows for central error diagnosis and configuration across all ECUs. CAN messages
are prioritized via IDs so that the highest priority IDs are non-interrupted. Each ECU contains a
chip for receiving all transmitted messages, decide relevance and act accordingly - this allows
easy modification and inclusion of additional nodes (e.g. CAN bus data loggers). The
applications include start/stop of vehicles, collision avoidance systems. The CAN bus systems
can provide speed up to 1Mbps.

Microwire

MICROWIRE is a 3Mbps [full-duplex] serial 3-wire interface essentially a subset of the SPI
interface. Microwire is a serial I/O port on microcontrollers, so the Microwire bus will also be
found on EEPROMs and other Peripheral chips. The 3 lines are SI (Serial Input), SO
(SerialOutput) and SK(Serial Clock). The Serial Input (SI) line to the microcontroller, SO is the
serial output line, and SK is the serial clock line. Data is shifted out on the falling edge of SK,
and is valued on the rising edge. SI is shifted in on the rising edge of SK. An additional bus
enhancement to MICROWIRE is called MICROWIRE/Plus. The main difference between the
two buses seems to be that MICROWIRE/Plus architecture within the microcontroller is more
complex. It supports speeds up to 3Mbps.

Asynchronous Serial Protocols


The asynchronous type of serial protocols are very essential when it comes to longer distance
reliable data transfer. Asynchronous communication does not require a timing clock that is
common to both devices. Each device independently listens and sends digital pulses that
represent bits of data at an agreed-upon rate. Asynchronous serial communication is sometimes
referred to as Transistor-Transistor Logic (TTL) serial, where the high voltage level is logic 1,
and the low voltage equates to logic 0. Almost every microcontroller on the market today has at
least one Universal Asynchronous Receiver-Transmitter (UART) for serial communication. The
examples are RS232, RS422, RS485 etc.

1. RS232

The RS232 (Recommended Standard 232) is very common protocol used to connect different
peripherals such as Monitors, CNCs etc. The RS232 comes in male and female connectors. The
RS232 is point-to-point topology with maximum one device connected and covers distance up to
15 meters at 9600 bps. Information on the RS-232 interface is transmitted digitally by logical 0
and 1. The logical "1" (MARK) corresponds to a voltage in the range from -3 to -15 V. The
logical "0" (SPACE) corresponds to a voltage in the range from +3 to +15 V. It comes in DB9
connector which has 9 pin outs such as TxD, RxD, RTS, CTS, DTR, DSR, DCD, GND.

RS232 is a standard protocol used for serial communication, it is used for connecting computer
and its peripheral devices to allow serial data exchange between them. As it obtains the voltage
for the path used for the data exchange between the devices. It is used in serial communication
up to 50 feet with the rate of 1.492kbps. As EIA defines, the RS232 is used for connecting Data
Transmission Equipment (DTE) and Data Communication Equipment (DCE).

Universal Asynchronous Data Receiver &Transmitter (UART) used in connection with


RS232 for transferring data between printer and computer. The microcontrollers are not able to
handle such kind of voltage levels, connectors are connected between RS232 signals. These
connectors are known as the DB-9 Connector as a serial port and they are of two type‟s Male
connector (DTE) & Female connector (DCE).

How RS232 Works?


RS232 works on the two-way communication that exchanges data to one another. There are two
devices connected to each other, (DTE) Data Transmission Equipment& (DCE) Data
Communication Equipment which has the pins like TXD, RXD, and RTS& CTS. Now,
from DTE source, the RTS generates the request to send the data. Then from the other
side DCE, the CTS, clears the path for receiving the data. After clearing a path, it will give a
signal to RTS of the DTE source to send the signal. Then the bits are transmitted
from DTE to DCE. Now again from DCE source, the request can be generated
by RTS and CTS of DTE sources clears the path for receiving the data and gives a signal to
send the data. This is the whole process through which data transmission takes place.

TXD TRANSMITTER

RXD RECEIVER

RTS REQUEST TO SEND

CTS CLEAR TO SEND

GND GROUND

For example: The signals set to logic 1, i.e., -12V. The data transmission starts from next bit and
to inform this, DTE sends start bit to DCE. The start bit is always „0‟, i.e., +12 V & next 5 to 9
characters is data bits. If we use parity bit, then 8 bits data can be transmitted whereas if parity
doesn‟t use, then 9 bits are being transmitted. The stop bits are sent by the transmitter whose
values are 1, 1.5 or 2 bits after the data transmission.

Mechanical Specification
For mechanical specifications, we have to study about two types of connectors that is DB-
25 and DB-9. In DB-25, there are 25 pins available which are used for many of the applications,
but some of the applications didn‟t use the whole 25 pins. So, the 9 pin connector is made for the
convenience of the devices and equipments.

What is Handshaking?
Handshaking is the process which is used to transfer the signal from DTE to DCE to make the
connection before the actual transfer of data. The messaging between transmitter & receiver can
be done by handshaking.

There are 3 types of handshaking processes named as:-

No Handshaking:

If there is no handshaking, then DCE reads the already received data while DTE transmits the
next data. All the received data stored in a memory location known as receiver‟s buffer. This
buffer can only store one bit so receiver must read the memory buffer before the next bit arrives.
If the receiver is not able to read the stored bit in the buffer and next bit arrives then the stored
bit will be lost.
As shown in below diagram, a receiver was unable to read the 4th bit till the 5th bit arrival and
this result overriding of 4th bit by 5th bit and 4th bit is lost.

Hardware Handshaking:

 It uses specific serial ports, i.e., RTS & CTS to control data flow.
 In this process, transmitter asks the receiver that it is ready to receive data then receiver
checks the buffer that it is empty, if it is empty then it will give signal to the transmitter
that I am ready to receive data.
 The receiver gives the signal to transmitter not to send any data while already received
data cannot be read.
 Its working process is same as above described in handshaking.

Software Handshaking:

 In this process, there are two forms, i.e., X-ON & X-OFF. Here, „X‟ is the transmitter.
 X-ON is the part in which it resumes the data transmission.
 X-OFF is the part in which it pauses the data transmission.
 It is used to control the data flow and prevent loss during transmission.
Applications of RS232 Communication

 RS232 serial communication is used in old generation PCs for connecting the peripheral
devices like mouse, printers, modem etc.
 Nowadays, RS232 is replaced by advanced USB.
 It is also used in PLC machines, CNC machines, and servo controllers because it is far
cheaper.
 It is still used by some microcontroller boards, receipt printers, point of sale system
(PoS), etc.

RS485

Since RS485 uses multi-point topology, it is most used in the industries and are industry
preferred protocol. RS422 can connect 32 line drivers and 32 receivers in a differential
configurations but with the help of additional repeaters and signal amplifiers up to 256 devices.
The RS-485 does not define a specific type of connector, but it is often a terminal block or a DB9
connector. The speed of operation also depends on the length of the line and can reach 10 Mbit /
s at 10 meters. The voltage on the lines is in the range from -7 V to +12 V. There are two types
of RS-485 such as half duplex mode RS-485 with 2 contacts and full duplex mode RS-485 with
4 contacts.
RS-485 adopts balanced transmission and differential reception, so it has the ability to suppress
common mode interference. In addition, the bus transceiver has high sensitivity and can detect
voltages as low as 200mv, so the transmission signal can be recovered from kilometers away.
RS485 advantage is the communication between multi-node systems.

RS-485 wiring methods include two-wire system and four-wire system. Four-wire system can
only realize point-to-point communication, which is rarely used now. The two-wire wiring
method is mostly used. This wiring method is a bus topology, and can connect up to 32 nodes on
the same bus. The commonly used RS485 circuit is shown in the following figure:
RS485 features
RS-485 electrical characteristics: logic "1" is represented by the voltage difference between the
two lines as +(2-6)V. Logic "0" is represented by the voltage difference between the two lines as
-(2-6)V. Lowering the interface signal level ratio RS-232-C can protect the chip in the interface
circuit from being damaged. And this level is compatible with TTL level, which can be easily
connected with TTL circuit.
The RS485 maximum transmission rate is 10Mbps.
The RS485 interface is strong, and the anti-noise interference is good.
Under the standard value, 485 maximum transmission distance is 4000 feet, which can actually
reach 3000 meters (theoretical data, in actual operation, the limit distance is only about 1200
meters). In addition, the RS-232-C interface allows only one transceiver to be connected to the
bus, which is called single-station capability. But the RS485 interface allows up to 128
transceivers to be connected on the bus, with multi-station capability. In this way, users can
easily establish a device network through a single RS-485 interface.
Why Is 4 20mA Used In Sensors?

RS485 communication principle


The RS485 signal will be decomposed into two lines with positive and negative symmetry (often
called A and B signal lines) before transmission. After reaching the receiving end, the two
signals are restored to the original signals. The positive level between the sending drivers A and
B is +2~6V, which is a positive 1 logic state. The negative level is -2~6V, which is a negative 0
logic state. Another signal ground C. There is also an “enable” terminal in RS485. The “enable”
terminal can control the disconnection and connection of the driver and the transmission line.
When the “enable” terminal is active, the sending driver is in a high-impedance state, which is
the third state different from logic “1” and “0”.
Difference between RS485 and RS232
RS232 is a single-ended operation, which is an unbalanced transmission method. The logic level
of the signal at the transceiver end is relative to the signal ground. RS232 was originally a one-
to-one communication between DET (Digital Terminal Equipment) and DCE (Data
Communication Equipment), and is generally used for full-duplex transmission. Of course, it can
also be used for half-duplex transmission.
RS485 RS232

Adopt balanced transmission – differential transmission Using unbalanced transmission – single-ended


communication

The transmission distance can reach 3000 meters The transmission distance does not exceed 20
meters

1 to 32 communication 1 to 1 communication

+2V~+6V means logic 1, -6V~-2V means logic 0 -15V-5V means logic 1, 5V~ 15V means logic 0

Two wires Three wires

Communication rate 20KB/S Communication rate 10MB/S


I2C Communication Protocol

I2C stands for Inter-Integrated Circuit. It is a bus interface connection protocol incorporated
into devices for serial communication. It was originally designed by Philips Semiconductor in
1982. Recently, it is a widely used protocol for short-distance communication. It is also known
as Two Wired Interface(TWI).
Working of I2C Communication Protocol :
It uses only 2 bi-directional open-drain lines for data communication called SDA and SCL. Both
these lines are pulled high.
Serial Data (SDA) – Transfer of data takes place through this pin.
Serial Clock (SCL) – It carries the clock signal.
I2C operates in 2 modes –
 Master mode
 Slave mode
Each data bit transferred on SDA line is synchronized by a high to the low pulse of each clock
on the SCL line.
I2C Serial Communication

Inter integrated circuit (I2C) two-line communication between different ICs or modules where
two lines are SDA (Serial Data Line) and SCL (Serial Clock Line). Both the lines must be
connected to a positive supply using a pull up resistor. I2C can deliver speed up to 400Kbps and
it uses 10 bit or 7 bit addressing system to target a specific device on the i2c bus so it can
connect up to 1024 devices. It has limited length communication and is ideal for onboard
communication. I2C networks are easy to setup since it uses only two wires and new devices can
simply be connected to the two common I2C bus lines.
According to I2C protocols, the data line can not change when the clock line is high, it can
change only when the clock line is low. The 2 lines are open drain, hence a pull-up resistor is
required so that the lines are high since the devices on the I2C bus are active low. The data is
transmitted in the form of packets which comprises 9 bits. The sequence of these bits are –
1. Start Condition – 1 bit
2. Slave Address – 8 bit
3. Acknowledge – 1 bit
Start and Stop Conditions :
START and STOP can be generated by keeping the SCL line high and changing the level of
SDA. To generate START condition the SDA is changed from high to low while keeping the
SCL high. To generate STOP condition SDA goes from low to high while keeping the SCL
high, as shown in the figure below.

Start and Stop Condition

Repeated Start Condition :


Between each start and stop condition pair, the bus is considered as busy and no master can
take control of the bus. If the master tries to initiate a new transfer and does not want to release
the bus before starting the new transfer, it issues a new START condition. It is called a
REPEATED START condition.
Read/Write Bit :
A high Read/Write bit indicates that the master is sending the data to the slave, whereas a low
Read/Write bit indicates that the master is receiving data from the slave.
ACK/NACK Bit :
After every data frame, follows an ACK/NACK bit. If the data frame is received successfully
then ACK bit is sent to the sender by the receiver.
Addressing :
The address frame is the first frame after the start bit. The address of the slave with which the
master wants to communicate is sent by the master to every slave connected with it. The slave
then compares its own address with this address and sends ACK.
I2C Packet Format :
In the I2C communication protocol, the data is transmitted in the form of packets. These
packets are 9 bits long, out of which the first 8 bits are put in SDA line and the 9th bit is
reserved for ACK/NACK i.e. Acknowledge or Not Acknowledge by the receiver.
START condition plus address packet plus one more data packet plus STOP
condition collectively form a complete Data transfer.
Features of I2C Communication Protocol :
 Half-duplex Communication Protocol –
Bi-directional communication is possible but not simultaneously.
 Synchronous Communication –
The data is transferred in the form of frames or blocks.
 Can be configured in a multi-master configuration.
 Clock Stretching –
The clock is stretched when the slave device is not ready to accept more data by holding
the SCL line low, hence disabling the master to raise the clock line. Master will not be able
to raise the clock line because the wires are AND wired and wait until the slave releases the
SCL line to show it is ready to transfer next bit.
 Arbitration –
I2C protocol supports multi-master bus system but more than one bus can not be used
simultaneously. The SDA and SCL are monitored by the masters. If the SDA is found high
when it was supposed to be low it will be inferred that another master is active and hence it
stops the transfer of data.
 Serial transmission –
I2C uses serial transmission for transmission of data.
 Used for low-speed communication.
Advantages :
 Can be configured in multi-master mode.
 Complexity is reduced because it uses only 2 bi-directional lines (unlike SPI
Communication).
 Cost-efficient.
 It uses ACK/NACK feature due to which it has improved error handling capabilities.
Limitations :
 Slower speed.
 Half-duplex communication is used in the I2C communication protocol.
SPI (Serial Port Interface)
The Serial Peripheral Interface (SPI) is a synchronous interface which allows several SPI
microcontrollers to be interconnected. In SPI, separate wires are required for data and clock line.
Also the clock is not included in the data stream and must be furnished as a separate signal. The
SPI may be configured either as master or as a slave. The four basic SPI signals (MISO, MOSI,
SCK and SS), Vcc and Ground are the part of data communication. So it needs 6 wires to send
and receive data from slave or master. Theoretically, the SPI can have unlimited number of
slaves. The data communication is configured in SPI registers. The SPI can deliver up to 10Mbps
of speed and is ideal for high speed data communication.

Most of the microcontrollers have inbuilt support for SPI and can be directly connected SPI
supported device:

SPI Specification
An SPI – Serial Peripheral Interface protocol system consists of one master device and one
or more slave devices. But in I2C, we can have one or more master devices and one or
more slave devices. The master is providing the SPI clock and the slave is receiving the
SPI clock from the master.
 SPI needs 4 wires at least. But some of the recent day devices support 3 pin mode and 4pin
modes also.
 MOSI – Master Out Slave In
 MISO – Master In Slave Out
 SCLK – Serial Clock
 SS/CS/CE – Salve Select/Chip Select/Chip Enable
 MOSI – Master Out Slave In is used to send the data from the master to the slave device.
 MISO – Master In Slave Out is used to receive the data from the slave to the master
device.
 SCLK – Serial Clock is the clock that is generated by the master device.
 SS/CS/CE – Salve Select/Chip Select/Chip Enable line is used to select the slave device in
the SPI bus interface.
 SPI protocol is a Full-duplex as this protocol has separate pins for incoming data and
outgoing data. So, we can transmit and receive the data at the same time.
 When you increase the number of slaves, then the Slave Select pin also increases. You can
easily understand this logic by using the below image.
 If you see the above picture, the master device has to use the 7 pins for 4 slave devices.
Yes, I can hear you. This is one of the disadvantages. In I2C, the number of pins won‟t
increase even if you increase the slave devices. To avoid this scenario, they have
introduced daisy chain logic. We will discuss that daisy chain later in this post.
 The communication (data transmission between the master and the slave) is synchronized
to the clock generated by the master. So, as it is synchronized using the clock, it doesn‟t
have to wait for a response before doing other operations. SPI devices support much higher
clock frequencies compared to I2C interfaces.

 Data Transmission
 To begin communication, the bus master configures the clock, using a frequency supported
by the slave device, typically up to a few MHz. Once the clock has been configured, then
the master makes the Slave select (SS/CS) pin LOW that initiates the transfer. When
multiple slaves are used, the master has to make the respective slave‟s Slave select (SS/CS)
pin LOW.
 During each SPI clock cycle, full-duplex data transmission occurs. The master sends a bit
on the MOSI pin and the slave reads it, while the slave sends a bit on the MISO pin and
the master reads it. This sequence is maintained even when only one-directional data
transfer is intended.
 Transmissions normally involve two shift registers of eight bits (mostly but size varies
based on the slaves), one in the master and one in the slave. Data is usually shifted out with
the most significant bit (MSB) first. On the clock edge, both master and slave shift out a bit
and output it on the transmission line to the counterpart. On the next clock edge, at each
receiver, the bit is sampled from the transmission line and set as a new least-significant bit
of the shift register. After the register bits have been shifted out and in, the master and
slave have exchanged register values. If more data needs to be exchanged, the shift
registers are reloaded and the process repeats. Transmission may continue for any number
of clock cycles.

Differentiate between I2C and SPI Protocol

I2C Protocol SPI Protocol


There are two bus lines required as a serial Three bus lines are needed; a data input line (SI1),
data line (SDA) and a serial clock line a data output line (SO1) and a serial clock line
(SCL). (SCK1) [plus 1 Chip Select (CS)].
It can support transfer speeds of around It is used at higher data rates (up to 10 MHz or
100kHz (original standard, or 400kHz using more).
the most recent standard)
It is used to be more efficient in multi- It is used to be more efficient in point-to-point
master, multi-slave applications. (single master, single slave) applications.
It is used for a built-in addressing scheme, It can lack built-in device addressing.
and straightforward.
It is used for more overhead when handling It can take less overhead when running a point-to-
point-to-point applications. point application.
It can be suited better for communication It can be served better for applications that are
with onboard devices that are accessed on an naturally thought of as data streams.
occasional basis.
It has an acknowledgement mechanism to It does not have an acknowledgement mechanism
confirm receipt of data. to confirm receipt of data.
Master Slave Synchronous Port

The Master Synchronous Serial Port (MSSP) module is a serial interface useful for
communicating with other peripheral or microcontroller devices. These peripheral devices may
be serial EEPROMs, shift registers, display drivers, A/D converters, etc. The MSSP module can
operate in one of two modes:
• Serial Peripheral Interface (SPI)
• Inter-Integrated Circuit (I2C)
- Full Master Mode
- Slave mode

Master Operation
The master can initiate the data transfer at any time because it controls the SCK. The master
determines when the slave (Processor 2) is to broadcast data by the software protocol. In
master mode the data is transmitted/received as soon as the SSPBUF register is written to. If
the SPI is only going to receive, the SDO output could be disabled (programmed as an input).
The SSPSR register will continue to shift in the signal present on the SDI pin at the
programmed clock rate. As each byte is received, it will be loaded into the SSPBUF register as
if a normal received byte (interrupts and status bits appropriately set). This could be useful in
receiver applications as a “line activity monitor” mode.
The clock polarity is selected by appropriately programming bit CKP (SSPCON<4>). This
then would give waveforms for SPI communication. In master mode, the SPI clock rate (bit
rate) is user programmable to be one of the following:
• FOSC/4 (or TCY)
• FOSC/16 (or 4 • TCY)
• FOSC/64 (or 16 • TCY)
• Timer2 output/2
This allows a maximum data rate of 5 Mbps (at 20 MHz).
Slave Operation
In slave mode, the data is transmitted and received as the external clock pulses appear on SCK.
When the last bit is latched, the interrupt flag bit SSPIF is set.
The clock polarity is selected by appropriately programming bit CKP (SSPCON<4>).
When in slave mode the external clock must meet the minimum high and low times.
In sleep mode, the slave can transmit and receive.
SSPCON2 – MSSP Control Register 2

 Bit 0 SEN : Start Condition or Stretch Enable bit. In master mode, setting this bit initiate
start condition on SCL & SDA pins and it will be automatically cleared by the hardware.
And in slave mode setting this bit enables clock stretching for both slave receive and
slave transmit. If it is cleared in slave mode, clock stretching is enabled only for slave
transmit.
 Bit 1 RSEN : Repeated start condition enable bit. This bit has application only in master
mode. Setting this bit will initiate repeated start condition on both SCL & SDA pins and
it will automatically cleared in hardware.
 Bit 2 PEN : Stop condition enable bit. This bit has application only in master mode.
Setting this bit will initiate stop condition on both SCL & SDA pins and it will be
automatically cleared in hardware.
 Bit 3 RCEN : Receive enable bit. This bit also has application only in master mode.
Setting this bit enables receive mode for I2C.
 Bit 4 ACKEN : Acknowledge sequence enable bit. Setting this bit initiates acknowledge
sequence on SCL & SDA lines and it will send ACKDT (see below) bit. This bit will be
automatically cleared in hardware. It has application only in master receive mode.
 Bit 5 ACKDT : Acknowledge data bit. 1 means not acknowledge and 0 means
acknowledge. This value will be transmitted when we set the ACKEN bit (above). This
bit has application only in master receive mode.
 Bit 6 ACKSTAT : Acknowledge status bit. 1 indicates that acknowledge was not
received from the slave and vice versa. This bit has application in master transmit mode
only.
 Bit 7 GCEN : General call enable bit. Setting this bit enables interrupt when a general
call address is received in the register SSPSR.

Explain with diagram SPI mode of MSSP structure of PIC 18F4550.


The Serial Peripheral Interface (SPI) is a synchronous serial communication protocol used for
short-distance communication between devices. The SPI communication involves a master
device and one or more slave devices. In a PIC microcontroller like the 18F4550, the SPI module
is typically controlled by the Master Synchronous Serial Port (MSSP) hardware module.

In SPI mode, the MSSP module includes the following components:


Control: This part manages the configuration and control of the SPI communication. It
includes registers for setting the mode of operation (Master or Slave), clock polarity, clock
phase, etc.

Data: This is the data buffer that holds the information to be transmitted or received. In SPI,
data is shifted out and in simultaneously.

Here's a brief explanation of how SPI works in the PIC 18F4550:

The Control block is responsible for configuring the MSSP module in either Master or Slave
mode. It also allows you to set the clock polarity and phase, which determine the clocking
strategy for data transmission.

In Master mode, the PIC microcontroller generates the clock signal (SCK) and selects the slave
device with a chip select (SS) signal. The Master sends data to the slave (MOSI - Master Out
Slave In) and receives data from the slave (MISO - Master In Slave Out).

In Slave mode, the microcontroller responds to the clock generated by the Master. The slave
also has MOSI and MISO lines, allowing bidirectional communication.

Remember that in SPI, data is transferred in a serial manner, one bit at a time. The clock signal
(SCK) determines the rate at which the bits are shifted.

SPI_Master

void SPI_Init_Master()
{

/* PORT definition for SPI pins*/


TRISBbits.TRISB0 =1; /* RB0 as input(SDI) */
TRISBbits.TRISB1=0; /* RB1 as output(SCK) */
TRISAbits.TRISA5=0; /* RA5 as a output(SS') */
TRISCbits.TRISC7=0; /* RC7 as output(SDO) */

/* To initialize SPI Communication configure following Register*/


CS = 1;

SSPSTAT=0x40; /* Data change on rising edge of clk , BF=0*/

SSPCON1=0x22; /* Master mode,Serial enable,


idle state low for clk, fosc/64 */
PIR1bits.SSPIF=0;

/* Disable the ADC channel which are on for multiplexed pin when
used as an input */

ADCON0=0; /* This is for de-multiplexed the


SCL and SDI from analog pins*/
ADCON1=0x0F; /* This makes all pins as digital I/O */
}

SPI_Slave

void SPI_Init_Slave()
{

/* PORT definition for SPI pins*/


TRISBbits.TRISB0 = 1; /* RB0 as input(SDI) */
TRISBbits.TRISB1 = 1; /* RB1 as input (SCK) */
TRISAbits.TRISA5 = 1; /* RA5 as a input (SS') */
TRISCbits.TRISC7 = 0; /* RC7 as output(SDO) */

/* To initialize SPI Communication configure following Register*/


CS = 1;

SSPSTAT=0x40; /* Data change on rising edge of clk , BF=0*/

SSPCON1=0x24; /* Slave mode,Serial enable, idle state


high for clk */
PIR1bits.SSPIF=0;

/* Disable the ADC channel which are on for multiplexed pin


when used as an input */

ADCON0=0; /* This is for de-multiplexed the SCL


and SDI from analog pins*/
ADCON1=0x0F; /* This makes all pins as digital I/O */
}

Explain with diagram I2C mode of MSSP structure of PIC 18F4550.


The Inter-Integrated Circuit (I2C) is another popular synchronous serial communication protocol used for
connecting multiple devices on the same bus. In a PIC microcontroller like the 18F4550, the I2C module
is typically controlled by the Master Synchronous Serial Port (MSSP) hardware module.

I2C Master

We need to write to SSPCON1 and SSPADD registers to configure MSSP module as I²C Master
and to set the clock frequency of I²C communication respectively.

I2C Slave

Similar to above, we need to write to SSPCON1 and SSPADD registers to configure MSSP
module in I²C slave mode and to set the slave device address respectively.
Clock generated by the master on SCL line will cause the data to shift in and shift out of the SSPSR
register which makes the I2C communication happen.

USART:
The Universal Synchronous Asynchronous Receiver Transmitter (USART) module is one of the
serial I/O modules for communication interfacing functions with other devices/units. USART is
also known as a Serial Communications Interface or SCI. The USART can be configured as a
full-duplex asynchronous system that can communicate with peripheral devices, such as CRT
terminals and personal computers, or it can be configured as a half-duplex synchronous system
that can communicate with peripheral devices, such as Analog-to-Digital (A/D) or Digital-to-
Analog (D/A) integrated circuits, serial EPROM‟s, and so on. Usually PIC 16F877 consists of
two USART modules (USART1, USART2). These ports can be configured in the following
modes:
• Asynchronous (full-duplex)
• Synchronous – Master (half-duplex)
• Synchronous – Slave (half-duplex)
The USART module also has a multi-processor communication capability using 9-bit address
detection.

USART Transmitter
USART transmitter (simply called TX) is commonly used for data transmission process. The
data transmission is possible through various digital formats. The path of the transmission vary
according to the requirements (e.g.: infrared, Bluetooth, etc.). A simple block diagram of a
USART transmitter is shown below. . The heart of the USART transmitter is the Transmit
(Serial) Shift Register (TSR). The shift register obtains its data from the Read/Write Transmit
Buffer, TXREG. The TXREG register is loaded with data in software. The TSR register is not
loaded until the Stop bit has been transmitted from the previous load. As soon as the Stop bit is
transmitted, the TSR is loaded with new data from the TXREG register (if available). The simple
block diagram of a USART transmitter is given below.

\
USART Receiver
The USART asynchronous receiver is a data reception unit which is used for data reception from
other communication medias such as RF modules, Bluetooth, infrared modules (IR), etc. The
simple block diagram of a USART receiver is shown in the figure below. The data is received on
the RC7/RX/DT pin and drives the data recovery block. The data recovery block is actually a
high-speed shifter, operating at x16 times the baud rate; whereas the main receive serial shifter
operates at the bit rate or at FOSC. Once Asynchronous mode is selected, reception is enabled by
setting bit CREN .The heart of the receiver is the Receive (Serial) Shift Register (RSR). After
sampling the Stop bit, the received data in the RSR is transferred to the RCREG register (if it is
empty). If the transfer is complete, flag bit, RCIF (PIR1<5>), is set.

Applications of USART Modules


1) Used for Bluetooth communications.
2) Widely used in Infrared (IR) communications.
3) USART modules used with other RF communication purposes – AM, FM, QPSK, PSK,
FSK, Wi-Fi, and so on.

USART Baud Rate Generator (BRG)


The baud rate generator (BRG) supports both the Asynchronous and Synchronous modes of the
USART modules. It is a dedicated 8-bit baud rate generator. The SPBRG register controls the
period of a free running 8-bit timer. In Asynchronous mode, bit BRGH also controls the baud
rate.
Real Time Clocks (RTC):
What are Real Time Clocks?

Real time clocks (RTC), as the name recommends are clock modules. The DS1307 real time
clock (RTC) IC is an 8 pin device using an I2C interface. The DS1307 is a low-power
clock/calendar with 56 bytes of battery backup SRAM. The clock/calendar provides seconds,
minutes, hours, day, date, month and year qualified data. The end date of each month is
automatically adjusted, especially for months with less than 31 days.

They are available as integrated circuits (ICs) and supervise timing like a clock and also operate
date like a calendar. The main advantage of RTC is that they have an arrangement of battery
backup which keeps the clock/calendar running even if there is power failure. An exceptionally
little current is required for keeping the RTC animated. We can find these RTCs in many
applications like embedded systems and computer mother boards, etc. In this article we are going
to see about one of the real time clock (RTC), i.e. DS1307.
Real-Time Clock (RTC) is used for tracking time and maintaining a calendar.

Many applications require keeping a record of time/date when certain events occur. RTCs are
useful in such applications.

RTCs come in handy in data logging applications. They are also used in devices like computers,
laptops, and mobile phones.
RTCs are powered by external batteries so that they can maintain time and data even in the case
of power failures.

RTCs have several registers that keep a track of time and date.

In order to use an RTC, we need to first program it with the current date and time. Once this is
done, the RTC registers can be read at any time to know the time and date.

DS1307 is an RTC that works on I2C protocol.

Pin Description of DS1307:

Pin 1, 2: Connections for standard 32.768 kHz quartz crystal. The internal oscillator circuitry is
intended for operation with a crystal having a specified load capacitance of 12.5pF. X1 is the
input to the oscillator and can alternatively be connected to an external 32.768 kHz oscillator.
The output of the internal oscillator, X2 is drifted if an external oscillator is connected to X1.

Pin 3: Battery input for any standard 3V lithium cell or other energy source. Battery voltage
should be between 2V and 3.5V for suitable operation. The nominal write protect trip point
voltage at which access to the RTC and user RAM is denied is set by the internal circuitry as
1.25 x VBAT nominal. A lithium battery with 48mAhr or greater will backup the DS1307 for
more than 10 years in the absence of power at 25ºC. UL recognized to ensure against reverse
charging current when utilized as a part of conjunction with a lithium battery.

Pin 4: Ground.

Pin 5: Serial data input/output. The input/output for the I2C serial interface is the SDA, which is
open drain and requires a pull up resistor, allowing a pull up voltage upto 5.5V. Regardless of the
voltage on VCC.

Pin 6: Serial clock input. It is the I2C interface clock input and is used in data synchronization.
Pin 7: Square wave/output driver. When enabled, the SQWE bit set to 1, the SQW/OUT pin
outputs one of four square-wave frequencies (1Hz, 4 kHz, 8 kHz, and 32 kHz). This is also open
drain and requires an external pull-up resistor. It requires application of either Vcc or Vb at to
operate SQW/OUT, with an allowable pull up voltage of 5.5V and can be left floating, if not
used.

Pin 8: Primary power supply. When voltage is applied within normal limits, the device is fully
accessible and data can be written and read. When a backup supply is connected to the device
and VCC is below VTP, read and writes are inhibited. However at low voltages, the timekeeping
function still functions.

Features:

 Programmable square wave output signal


 Automatic power-fail detect and switch circuitry
 Consumes less than 500nA in battery backup mode with oscillator running
 Available in 8-pin DIP or SOIC
 Underwriters Laboratory (UL) recognized
 Real-time clock (RTC) counts seconds, minutes, hours, date of the month, month, day of the
week, and year with leap-year compensation valid up to 2100
 56-byte non-volatile RAM for data storage
 Two-wire interface (I2C)
Real Time Clock RTC DS1307 interfacing with PIC18F4550

Programming steps for RTC DS1307


Initially, while using RTC first time, we have to set the clock and calendar values, then RTC
always keeps updating this clock and calendar values.

We will set the RTC clock and calendar values in 1st step and in 2nd step, we will read these
values.

Step1: Setting Clock and Calendar to RTC DS1307

 In RTC coding, we require the first RTC device address (slave address) through which
the microcontroller wants to communicate with the DS1307.
 DS1307 RTC device address is 0xD0 (given in datasheet).
 Initialize I2C in PIC18F4550.
 Start I2C communication with device writes address i.e. 0xD0.
 Then, Send the Register address of Seconds which is 0x00, then send the value of
seconds to write in RTC. RTC address gets auto-incremented so next, we only have to
send the values of minutes, hours, day, date, month, and year.
 And stop the I2C communication.

Step2: Reading Time and Date value from RTC DS1307

 In the second step, we will read the data from the RTC, i.e. second, minute, hours, etc.
 Start the I2C communication with device writes address i.e. 0xD0.
 Then write the register value from where we have to read the data (we read from location
00 i.e. read the second).
 Then send repeated start with device read address i.e. 0xD1.
 Now Read the data with acknowledgment from location 00.
 For reading the last location always read with the negative acknowledgment, then the
device will understand this is the last data to read from the device.
 For read next Byte, the location of the register address will get auto-incremented.

#include <stdio.h>
#include "Configuration_Header_File.h"
#include "16x2_LCD_4bit_File.h"
#include <pic18f4550.h>
#include "I2C_Master_File.h"

#define device_id_write 0xD0


#define device_id_read 0xD1

int sec,min,hour;
int Day,Date,Month,Year;

void RTC_Read_Clock(char read_clock_address)


{
I2C_Start(device_id_write);
I2C_Write(read_clock_address); /* address from where time needs to be read*/
I2C_Repeated_Start(device_id_read);
sec = I2C_Read(0); /*read data and send ack for continuous reading*/
min = I2C_Read(0); /*read data and send ack for continuous reading*/
hour= I2C_Read(1); /*read data and send nack for indicating stop reading*/

void RTC_Read_Calendar(char read_calendar_address)


{
I2C_Start(device_id_write);
I2C_Write(read_calendar_address); /* address from where time needs to be read*/
I2C_Repeated_Start(device_id_read);
Day = I2C_Read(0); /*read data and send ack for continuous reading*/
Date = I2C_Read(0); /*read data and send ack for continuous reading*/
Month = I2C_Read(0); /*read data and send ack for continuous reading*/
Year = I2C_Read(1); /*read data and send nack for indicating stop reading*/
I2C_Stop();
}

void main()
{

char secs[10],mins[10],hours[10];
char date[10],month[10],year[10];
char Clock_type = 0x06;
char AM_PM = 0x05;
char days[7] = {'S','M','T','W','t','F','s'};
OSCCON=0x72; /*Use internal oscillator and
*set frequency to 8 MHz*/
I2C_Init(); /*initialize I2C protocol*/
LCD_Init(); /*initialize LCD16x2*/
LCD_Clear();
MSdelay(10);
while(1)
{
RTC_Read_Clock(0); /*gives second,minute and hour*/
I2C_Stop();
if(hour & (1<<Clock_type)){ /* check clock is 12hr or 24hr */

if(hour & (1<<AM_PM)){ /* check AM or PM */


LCD_String_xy(1,14,"PM");
}
else{
LCD_String_xy(1,14,"AM");
}

hour = hour & (0x1f);


sprintf(secs,"%x ",sec); /*%x for reading BCD format from RTC DS1307*/
sprintf(mins,"%x:",min);
sprintf(hours,"Tim:%x:",hour);
LCD_String_xy(0,0,hours);
LCD_String(mins);
LCD_String(secs);
}
else{

hour = hour & (0x3f);


sprintf(secs,"%x ",sec); /*%x for reading BCD format from RTC DS1307*/
sprintf(mins,"%x:",min);
sprintf(hours,"Tim:%x:",hour);
LCD_String_xy(0,0,hours);
LCD_String(mins);
LCD_String(secs);
}

RTC_Read_Calendar(3); /*gives day, date, month, year*/


I2C_Stop();
sprintf(date,"Cal %x-",Date);
sprintf(month,"%x-",Month);
sprintf(year,"%x ",Year);
LCD_String_xy(2,0,date);
LCD_String(month);
LCD_String(year);

/* find day */
switch(days[Day])
{
case 'S':
LCD_String("Sun");
break;
case 'M':
LCD_String("Mon");
break;
case 'T':
LCD_String("Tue");
break;
case 'W':
LCD_String("Wed");
break;
case 't':
LCD_String("Thu");
break;
case 'F':
LCD_String("Fri");
break;
case 's':
LCD_String("Sat");
break;
default:
break;

}
}
EEPROM interface with I2C

What is an EEPROM?

An EEPROM is a non-volatile memory that means it can store the data permanently without any
power supply. EEPROM stands for Electrically Erasable Programmable Read-Only Memory.
We can erase the EEPROM data by the UV eraser.
An EEPROM is slower than the flash memory. In flash memory, we can erase the whole sector
at a time but in the case of EEPROM, we can erase a single byte at the time.
Some microcontrollers confine a small amount of EEPROM to store the extra bytes which are
required in the program, for example, usernames and passwords.

 A0, A1, A2 – Chip Address Inputs : These inputs are used for multiple device
operations. The logic levels on these input pins are compared with the corresponding bits
in the slave address and the chip is selected if the compare is true. Thus up to eight
devices can be connected to same bus using different chip select bit combinations.
 WP – Write Protect : When this pin is kept LOW (grounded) normal read and write
operations are possible but when it is HIGH (Vcc) write operations will be inhibited. The
internal PULL DOWN resistor of this pin keep the device unprotected when it is left
floating.
 Vcc and Vss : Vcc is the positive DC supply pin. The device is able to work with in 1.8
to 5.5V range. Vss is the ground pin (0v).
 SDA – Serial Data : This is bidirectional pin used to transfer data and address to and
from the device.
 SCL – Serial Clock : This pin is used to synchronize data transfer through SDA.
Design of Traffic Light Controller:

The above figure shows the complete block diagram of the system to be implemented. An
external power supply is applied to PIC18F4550 which is used to drive the motor at different
times. There are three led‟s(traffic signals) in the system that indicate the system to be controlled
by motor and it depends on which led is glowing and their respective action is performed
accordingly. The traffic signals are controlled using PIC18F4550 microcontroller. The DC
motors are connected to the controller. When the traffic signal becomes red the DC motor starts
rotating and the panel comes up and blocks the roads and prohibits vehicles on moving further.
When the signal becomes yellow the DC motor starts rotating in opposite direction and this
brings the panel down. When the signal becomes green the roads are finally free and vehicles
start moving. This cycle repeats on all roads thus preventing the accidents.

You might also like