0% found this document useful (0 votes)
118 views46 pages

Basics of I2C Communication - Hardware, Data Transfer, Configuration

This document provides an overview of I2C communication, including: - I2C uses only two bidirectional lines (SDA and SCL) to connect multiple devices on a circuit board. One device acts as the master that controls data transfer. - Data transfer involves start/stop conditions and uses addressing and ACK/NACK bits to ensure reliable communication between the master and addressed slave device(s). - The master can initiate transfers to send data to or receive data from slave devices using the same basic protocol and line control.

Uploaded by

Sathish Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
118 views46 pages

Basics of I2C Communication - Hardware, Data Transfer, Configuration

This document provides an overview of I2C communication, including: - I2C uses only two bidirectional lines (SDA and SCL) to connect multiple devices on a circuit board. One device acts as the master that controls data transfer. - Data transfer involves start/stop conditions and uses addressing and ACK/NACK bits to ensure reliable communication between the master and addressed slave device(s). - The master can initiate transfers to send data to or receive data from slave devices using the same basic protocol and line control.

Uploaded by

Sathish Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 46

Basics of I2C Communication | Hardware, Data Transfer,

Configuration
In this article, we will learn about what I2C communication protocol is, its
hardware, how data is transferred and different configurations in which it
operates.

Table of Contents
 Introduction to I2C Communication
 Features
 Hardware
o The physical I2C Bus
o Master and Slave Devices
 Data Transfer Protocol
o Start Condition
o Address Block
o Read/Write Bit
o ACK/NACK Bit
o Data Block
o Stop Condition
 How I2C Communication Practically Works?
o Sending Data to a Slave Device
o Reading Data from a Slave Device
o Concept of clock stretching
Introduction to I2C Communication

I2C communication is the short form for inter-integrated circuits. It is a


communication protocol developed by Philips Semiconductors for the transfer
of data between a central processor and multiple ICs on the same circuit board
using just two common wires.

Owing to its simplicity, it is widely adopted for communication between


microcontrollers and sensor arrays, displays, IoT devices, EEPROMs etc.

This is a type of synchronous serial communication protocol. It means that data


bits are transferred one by one at regular intervals of time set by a reference
clock line.

Features
The following are some of the important features of I2C communication
protocol:

 Only two common bus lines (wires) are required to control any device/IC
on the I2C network
 No need of prior agreement on data transfer rate like in UART
communication. So the data transfer speed can be adjusted whenever
required
 Simple mechanism for validation of data transferred
 Uses 7-bit addressing system to target a specific device/IC on the I2C bus
 I2C networks are easy to scale. New devices can simply be connected to
the two common I2C bus lines

Hardware

The physical I2C Bus

I2C Bus (Interface wires) consists of just two wires and are named as Serial
Clock Line (SCL) and Serial Data Line (SDA). The data to be transferred is sent
through the SDA wire and is synchronized with the clock signal from SCL. All
the devices/ICs on the I2C network are connected to the same SCL and SDA
lines as shown below:

Both the I2C bus lines (SDA, SCL) are operated as open drain drivers. It means
that any device/IC on the I2C network can drive SDA and SCL low, but they
cannot drive them high. So, a pull up resistor is used for each bus line, to keep
them high (at positive voltage) by default.
The reason for using an open-drain system is that there will be no chances of
shorting, which might happen when one device tries to pull the line high and
some other device tries to pull the line low.

Master and Slave Devices

The devices connected to the I2C bus are categorized as either masters or
slaves. At any instant of time only a single master stays active on the I2C bus. It
controls the SCL clock line and decides what operation is to be done on the
SDA data line.

All the devices that respond to instructions from this master device are slaves.
For differentiating between multiple slave devices connected to the same I2C
bus, each slave device is physically assigned a permanent 7-bit address.

When a master device wants to transfer data to or from a slave device, it


specifies this particular slave device address on the SDA line and then proceeds
with the transfer. So effectively communication takes place between the master
device and a particular slave device.

All the other slave devices doesn’t respond unless their address is specified by
the master device on the SDA line.

Data Transfer Protocol

The following protocol (set of rules) is followed by master device and slave
devices for the transfer of data between them.

Data is transferred between the master device and slave devices through a single
SDA data line, via patterned sequences of 0’s and 1’s (bits). Each sequence of
0’s and 1’s is termed as a transaction and the data in each transaction is
structured as below:

Start Condition

Whenever a master device/IC decides to start a transaction, it switches the SDA


line from high voltage level to a low voltage level before the SCL line switches
from high to low.

Once a start condition is sent by the master device, all the slave devices get
active even if they are in sleep mode, and wait for the address bits.

Address Block

It comprises of 7 bits and are filled with the address of slave device to/from
which the master device needs send/receive data. All the slave devices on the
I2C bus compare these address bits with their address.

Read/Write Bit
This bit specifies the direction of data transfer. If the master device/IC need to
send data to a slave device, this bit is set to ‘0’. If the master IC needs to receive
data from the slave device, it is set to ‘1’.

ACK/NACK Bit

It stands for Acknowledged/Not-Acknowledged bit. If the physical address of


any slave device coincides with the address broadcasted by the master device,
the value of this bit is set to ‘0’ by the slave device. Otherwise it remains at
logic ‘1’ (default).

Data Block

It comprises of 8 bits and they are set by the sender, with the data bits it needs
to transfer to the receiver. This block is followed by an ACK/NACK bit and is
set to ‘0’ by the receiver if it successfully receives data. Otherwise it stays at
logic ‘1’.

This combination of data block followed by ACK/NACK bit is repeated until


the data is completely transferred.

Stop Condition

After required data blocks are transferred through the SDA line, the master
device switches the SDA line from low voltage level to high voltage level
before the SCL line switches from high to low.

NOTE: Logic ‘0’ or setting a bit to ‘0’ is equivalent to applying low voltage on


the SDA line and vice versa.

How I2C Communication Practically Works?


An I2C communication/transaction is initiated by a master device either to send
data to a slave device or to receive data from it. Let us learn about working of
both the scenarios in detail.

Sending Data to a Slave Device

The following sequence of operations take place when a master device tries to
send data to a particular slave device through I2C bus:

 The master device sends the start condition


 The master device sends the 7 address bits which corresponds to the slave
device to be targeted
 The master device sets the Read/Write bit to ‘0’, which signifies a write
 Now two scenarios are possible:

o If no slave device matches with the address sent by the master


device, the next ACK/NACK bit stays at ‘1’ (default). This signals
the master device that the slave device identification is unsuccessful.
The master clock will end the current transaction by sending a Stop
condition or a new Start condition
o If a slave device exists with the same address as the one specified
by the master device, the slave device sets the ACK/NACK bit to ‘0’,
which signals the master device that a slave device is successfully
targeted
 If a slave device is successfully targeted, the master device now
sends 8 bits of data which is only considered and received by the targeted
slave device. This data means nothing to the remaining slave devices
 If the data is successfully received by the slave device, it sets the
ACK/NACK bit to ‘0’, which signals the master device to continue
 The previous two steps are repeated until all the data is transferred
 After all the data is sent to the slave device, the master device
sends the Stop condition which signals all the slave devices that the
current transaction has ended

The below figure represents the overall data bits sent on the SDA line and the
device that controls each of them:
Reading Data from a Slave Device

The sequence of operations remain the same as in previous scenario except for
the following:

 The master device sets the Read/Write bit to ‘1’ instead of ‘0’ which
signals the targeted slave device that the master device is expecting data
from it
 The 8 bits corresponding to the data block are sent by the slave device
and the ACK/NACK bit is set by the master device
 Once the required data is received by the master device, it sends a NACK
bit. Then the slave device stops sending data and releases the SDA line

If the master device to read data from specific internal location of a slave
device, it first sends the location data to the slave device using the steps in
previous scenario. It then starts the process of reading data with a repeated start
condition.

The below figure represents the overall data bits sent on the SDA line and the
device that controls each of them:
Concept of clock stretching

Let say the master device started a transaction and sent address bits of a
particular slave device followed by a Read bit of ‘1’. The specific slave device
needs to send an ACK bit, immediately followed by data.

But if the slave device needs some time to fetch and send data to master device,
during this gap, the master device will think that the slave device is sending
some data.

To prevent this, the slave device holds the SCL clock line low until it is ready to
transfer data bits. By doing this, the slave device signals the master device to
wait for data bits until the clock line is released.

That’s it for this article. Take a look at the below projects to get an idea on how
I2C communication is practically implemented, between
microcontrollers/Arduinos and different sensors:

Basics of Serial Peripheral Interface (SPI)


Table of Contents
 Introduction
 How SPI Works?
 SPI Hardware
 SPI Modes of Operation
o Mode 0:
o Mode 1:
o Mode 2:
o Mode 3:
 SPI Configurations
 Applications of SPI
 Advantages
 Disadvantages
Introduction

Serial Peripheral Interface or SPI is a synchronous serial communication


protocol that provides full – duplex communication at very high speeds. Serial
Peripheral Interface (SPI) is a master – slave type protocol that provides a
simple and low cost interface between a microcontroller and its peripherals.

SPI Interface bus is commonly used for interfacing microprocessor or


microcontroller with memory like EEPROM, RTC (Real Time Clock), ADC
(Analog – to – Digital Converters), DAC (Digital – to – Analog Converters),
displays like LCDs, Audio ICs, sensors like temperature and pressure, memory
cards like MMC or SD Cards or even other microcontrollers.

We have seen about UART in the previous article. In UART (or any common
serial port), where the communication happens over RX and TX line, there is no
clock signal i.e. it is an asynchronous communication. In this type of
communication, there is no control over the data sent or whether the transmitter
and receiver have same data rates.

In order to overcome this, UART uses synchronisation bits i.e. Start bit and
Stop bits and also a pre agreed data transfer speeds (typically 9600 bps). If the
baud rates of transmitter and receiver are not matched, the data sent from the
transmitter will not reach the receiver properly and often garbage or junk values
are received.
For short distance communication, Synchronous Serial Communication would
be a better choice and in that Serial Peripheral Interface or SPI in particular is
the best choice. When we say short distance communication, it often means
communication with in a device or between the devices on the same board
(PCB).

The other type of Synchronous Serial Communication Protocol is I2C (Inter –


Integrated Communication, often called as I Squared C or I Two C). For this
article, we will focus on SPI.

SPI is a Synchronous type serial communication i.e. it uses a dedicated clock


signal to synchronise the transmitter and receiver or Master and Slave, speaking
in SPI terms. The transmitter and receiver are connected with separate data and
clock lines and the clock signal will help the receiver when to look for data on
the bus.
The clock signal must be supplied by the Master to the slave (or all the slaves in
case of multiple slave setup). There are two types of triggering mechanisms on
the clock signal that are used to intimate the receiver about the data: Edge
Triggering and Level Triggering.

The most commonly used triggering is edge triggering and there are two types:
rising edge (low to high transition on the clock) and falling edge (high to low
transition). Depending on how the receiver is configured, up on detecting the
edge, the receiver will look for data on the data bus from the next bit. S

Since both the clock and data are sent by the Master (or transmitter), we need
not worry about the speed of data transfer.

What makes SPI so popular among other Synchronous Serial Communication


protocols (or any serial communication for that matter) is that it provides a high
speed secured data transfer with reasonably simple hardware like shift registers
at relatively less cost.

How SPI Works?

SPI or Serial Peripheral Interface was developed by Motorola in the 1980’s as a


standard, low – cost and reliable interface between the Microcontroller
(microcontrollers by Motorola in the beginning) and its peripheral ICs.

Because of its simple interface, flexibility and ease of use, SPI has become a
standard and soon other semiconductor manufacturers started implementing it in
their chips.

In SPI protocol, the devices are connected in a Master – Slave relationship in a


multi – point interface. In this type of interface, one device is considered the
Master of the bus (usually a Microcontroller) and all the other devices
(peripheral ICs or even other Microcontrollers) are considered as slaves.

In SPI protocol, there can be only one master but many slave devices.

The SPI bus consists of 4 signals or pins. They are

 Master – Out / Slave – In (MOSI)

 Master – In / Slave – Out (MISO)


 Serial Clock (SCLK) and

 Chip Select (CS) or Slave Select (SS)

NOTE: Different manufacturers uses different nomenclature for the SPI bus.


Refer the data sheet for exact information.

Since, the SPI bus is implemented using 4 signals or wires, it is sometimes


called as Four Wire Interface. Let us first see a simple interface between a
single master and single slave that are connected using SPI protocol and then
we will explain about the 4 wires.

The following image depicts a Master (Processor) connected to a Slave


(Peripheral) using SPI bus.

Master – Out / Slave – In or MOSI, as the name suggests, is the data generated
by the Master and received by the Slave. Hence, MOSI pins on both the master
and slave are connected together. Master – In / Slave – Out or MISO is the data
generated by Slave and must be transmitted to Master.

MISO pins on both the master and slave are ties together. Even though the
Signal in MISO is produced by the Slave, the line is controlled by the Master.
The Master generates a clock signal at SCLK and is supplied to the clock input
of the slave. Chip Select (CS) or Slave Select (SS) is used to select a particular
slave by the master.

Since the clock is generated by the Master, the flow of data is controlled by the
master. For every clock cycle, one bit of data is transmitted from master to slave
and one bit of data is transmitted from slave to master.
This process happen simultaneously and after 8 clock cycles, a byte of data is
transmitted in both directions and hence, SPI is a full – duplex communication.

If the data has to be transmitted by only one device, then the other device has to
send something (even garbage or junk data) and it is up to the device whether
the transmitted data is actual data or not.

This means that for every bit transmitted by one device, the other device has to
send one bit data i.e. the Master simultaneously transmits data on MOSI line
and receive data from slave on MISO line.

If the slave wants to transmit the data, the master has to generate the clock
signal accordingly by knowing when the slave wants to send the data in
advance. If more than one slave has to be connected to the master, then the
setup will be something similar to the following image.

Even though multiple slaves are connected to the master in the SPI bus, only
one slave will be active at any time. In order to select the slave, the master will
pull down the SS (Slave Select) or CS (Chip Select) line of the corresponding
slave.

Hence, there must by a separate CS pin on the Master corresponding to each of


the slave device. We need to pull down the SS or CS line to select the slave
because this line is active low.
SPI Hardware

The hardware requirement for implementing SPI is very simple when compared
to UART and I2C. Consider a Master and a single Slave are connected using
SPI bus. The following image shows the minimal system requirements for both
the devices.

From the image, the Master device consists of a Shift Register, a data latch and
a clock generator. The slave consists of similar hardware: a shift register and a
data latch. Both the shift registers are connected to form a loop. Usually, the
size of the register is 8 – bits but higher size registers of 16 – bits are also
common.

During the positive edge of the clock signal, both the devices (master and slave)
read input bit into LSB of the register. During the negative cycle of the clock
signal, both the master and slave places a bit on its corresponding output from
the MSB of the shift register.

Hence, for each clock cycle, a bit of data is transferred in each direction i.e.
from master to slave and slave to master. So, for a byte of data to be transmitted
from each device, it will take 8 clock cycles.

SPI Modes of Operation

We have already seen that it is the job of the Master device to generate the clock
signal and distribute it to the slave in order to synchronise the data between
master and slave. The work of master doesn’t end at generating clock signal at a
particular frequency.
In fact, the master and slave have to agree on certain synchronization protocols.
For this, two features of the clock i.e. the Clock Polarity (CPOL or CKP) and
Clock Phase (CPHA) come in to picture.

Clock Polarity determines the state of the clock. When CPOL is LOW, the
clock generated by the Master i.e. SCK is LOW when idle and toggles to HIGH
during active state (during a transfer). Similarly, when CPOL is HIGH, SCK is
HIGH during idle and LOW during active state.

Clock Phase determines the clock transition i.e. rising (LOW to HIGH) or
falling (HIGH to LOW), at which the data is transmitted. When CPHA is 0, the
data is transmitted on the rising edge of the clock. Data is transmitted on the
falling edge when CPHA is 1.

Depending on the values of Clock Polarity (CPOL) and Clock Phase (CPHA),
there are 4 modes of operation of SPI: Modes 0 through 3.

Mode 0:

Mode 0 occurs when Clock Polarity is LOW and Clock Phase is 0 (CPOL = 0
and CPHA = 0). During Mode 0, data transmission occurs during rising edge of
the clock.

Mode 1:

Mode 1 occurs when Clock Polarity is LOW and Clock Phase is 1 (CPOL = 0
and CPHA = 1). During Mode 1, data transmission occurs during falling edge of
the clock.

Mode 2:

Mode 2 occurs when Clock Polarity is HIGH and Clock Phase is 0 (CPOL = 1
and CPHA = 0). During Mode 2, data transmission occurs during rising edge of
the clock.

Mode 3:

Mode 3 occurs when Clock Polarity is HIGH and Clock Phase is 1 (CPOL = 1
and CPHA = 1). During Mode 3, data transmission occurs during rising edge of
the clock.
SPI Configurations

There are two types of configurations in which the SPI devices can be
connected in an SPI bus. They are Independent Slave Configuration and Daisy
Chain Configuration.

In Independent Slave Configuration, the master has dedicated Slave Select


Lines for all the slaves and each slave can be selected individually. All the clock
signals of the slaves are connected to the master SCK.

Similarly, all the MOSI pins of all the slaves are connected to the MOSI pin of
the master and all the MISO pins of all the slaves are connected to the MISO
pin of the master.

In Daisy Chain Configuration, only a single Slave Select line is connected to all
the slaves. The MOSI of the master is connected to the MOSI of slave 1. MISO
of slave 1 is connected to MOSI of slave 2 and so on. The MISO of the final
slave is connected to the MISO of the master.

Consider the master transmits 3 bytes of data in to the SPI bus. First, the 1st
byte of data is shifted to slave 1. When the 2nd byte of data reaches slave 1, the
first byte is pushed in to slave 2.

Finally, when the 3rd byte of data arrives in to the first slave, the 1st byte of
data is shifted to slave 3 and the second byte of data is shifted in to second
slave.

If the master wants to retrieve information from the slaves, it has to send 3 bytes
of junk data to the slaves so that the information in the slaves comes to the
master.

Applications of SPI
 Memory: SD Card , MMC , EEPROM , Flash
 Sensors: Temperature and Pressure
 Control Devices: ADC , DAC , digital POTS and Audio Codec.
 Others: Camera Lens Mount, touchscreen, LCD, RTC, video game
controller, etc.
Advantages
 SPI is very simple to implement and the hardware requirements are not
that complex.
 Supports full – duplex communication at all times.
 Very high speed of data transfer.
 No need for individual addresses for slaves as CS or SS is used.
 Only one master device is supported and hence there is no chance of
conflicts.
 Clock from the master is configured based on speed of the slave and
hence slave doesn’t have to worry about clock.
Disadvantages
 Each additional slave requires an additional dedicated pin on master for
CS or SS.
 There is no acknowledgement mechanism and hence there is no
confirmation of receipt of data.
 Slowest device determines the speed of transfer.
 There are no official standards and hence often used in application
specific implementations.
 There is no flow control.

Basics of UART Communication

UART or Universal Asynchronous Receiver Transmitter is a dedicated


hardware associated with serial communication. The hardware for UART can
be a circuit integrated on the microcontroller or a dedicated IC. This is contrast
to SPI or I2C, which are just communication protocols.

UART is one of the most simple and most commonly used Serial
Communication techniques. Today, UART is being used in many applications
like GPS Receivers, Bluetooth Modules, GSM and GPRS Modems, Wireless
Communication Systems, RFID based applications etc.

If you remember older computer systems, devices like Mouse, Printer and
Modem are connected using a heavy connectors at the back. All these devices
communicated using UART.
Even though USB has replaced all types of communication standards on
computers and other devices, UART is still being used in the above mentioned
applications.

Almost all microcontrollers have dedicated UART hardware built in to their


architecture. The main reason for integrating the UART hardware in to
microcontrollers is that it is a serial communication and requires only two wires
for communication.

Before going in to further explanation of UART, how it works and steps


involved in transmission and reception of data, we will try to recollect some
information about Serial Communication and a small comparison between serial
and parallel communications.

Table of Contents
 Brief Note on Parallel and Serial Communication
 Introduction to UART Communication
 How UART Works?
 Structure of Data Packet or Frame
 Rules of UART
 Advantages of UART
 Disadvantages of UART
Brief Note on Parallel and Serial Communication

Transfer of Digital Data from one device to another can be achieved in two
ways: Parallel Data Transfer and Serial Data Transfer. In parallel data transfer,
all the bits are transferred from the source to destination at once.

This is possible because parallel data transfer uses multiple lanes or wires
between the transmitter and receiver in order to transfer the data.
Parallel Data Transfer methods are faster and expensive as they needs more
hardware and a lot of wires. Olden day’s printers are the best example for
external parallel communication. Other examples are RAM, PCI, etc.

With the progress in integrated circuit technology, the digital IC’s are becoming
smaller and faster and as a result the transfer rates in Parallel Communication
with multiple lanes have reached a bottle neck.

Serial Communication on the hand, transfers data bit by bit using a single line
or wire. For two way communication between the transmitter and receiver, we
need just two wires for successful serial data transfer.

Since serial communication needs less circuitry and wires, the cost of
implementing is less. As a result, using serial communication in complex
circuitry might be more practical than parallel communication.
But the only concern with serial data transfers is speed. Since the data transfer
occurs over a single line, the speed of transfer in serial communication is less
than that of parallel communication. Now – a – days, the speed of serial data
transfer isn’t a concern as advancements in technology have led to faster
transfer speeds.

Introduction to UART Communication

UART or Universal Asynchronous Receiver Transmitter is a serial


communication device that performs parallel – to – serial data conversion at the
transmitter side and serial – to – parallel data conversion at the receiver side. It
is universal because the parameters like transfer speed, data speed, etc. are
configurable.

As mentioned in the introduction section, UART is a piece of hardware that acts


as a bridge between the processor and the serial communication protocol or
port. The following image shows this interface briefly. The serial
communication can be anything like USB, RS – 232, etc.
The letter ‘A’ in UART stands for Asynchronous i.e. there is no clock signal to
synchronize or validate the data transmitted from transmitter and received by
the receiver (Asynchronous Serial Communication).

This is in contrast to Synchronous Serial Communication, which uses a clock


signal that is shared between the transmitter and receiver in order to
“Synchronize” the data between them.

If there is no clock (or any other timing signal) between the transmitter and
receiver, then how does the receiver know when to read the data?

In UART, the transmitter and receiver must agree on timing parameters


beforehand. Also, UART uses special bits at the beginning and ending of each
data word to synchronize the transmitter and receiver. More about these special
bits in the later sections.

In UART based Serial Communication, the transmitter and receiver


communicate in the following manner. The UART on the sender device i.e. the
transmitting UART receives parallel data from the CPU (microprocessor or
microcontroller) and converts it in to serial data.

This serial data is transmitted to the UART on the receiver device i.e. receiving
UART. The receiving UART, upon receiving the serial data, converts it back to
parallel data and gives it to the CPU.
The pin on the transmitting UART, which transmits the serial data is called TX
and the pin on the receiving UART, which receives the serial data is called RX.

Since the UART involves parallel – to – serial and serial – to – parallel data
conversion, shift registers are an essential part of the UART hardware (two shift
registers to be specific: Transmitter Shift Register and Receiver Shift Register).

How UART Works?

In UART Serial Communication, the data is transmitted asynchronously i.e.


there is no clock or other timing signal involved between the sender and
receiver. Instead of clock signal, UART uses some special bits called Start and
Stop bits.

These bits are added to the actual data packet at the beginning and end
respectively. These additional bits allows the receiving UART to identify the
actual data.

The image above shows a typical UART connection. The transmitting UART
receives data from the controlling device through the data bus. The controlling
device can be anything like a CPU of a microprocessor or a microcontroller,
memory unit like a RAM or ROM, etc. The data received by the transmitting
UART from the data bus is parallel data.

To this data, the UART adds Start, Parity and Stop bits in order to convert it
into a data packet. The data packet is then converted from parallel to serial with
the help of shift register and is transmitted bit – by – bit from the TX pin.
The receiving UART receives this serial data at the RX pin and detects the
actual data by identifying the start and stop bits. Parity bit is used to check the
integrity of the data.

Up on separating the start, parity and stop bits from the data packet, the data is
converted to parallel data with the help of shift register. This parallel data is sent
to the controller at the receiving end through a data bus.

Structure of Data Packet or Frame

The data in UART serial communication is organised in to blocks called


Packets or Frames. The structure of a typical UART Data Packet or the standard
framing of the data is shown in the following image.

Let us see about each piece of the frame.

Start Bit: Start bit is a synchronisation bit that is added before the actual data.
Start bit marks the beginning of the data packet. Usually, an idle data line i.e.
when the data transmission line is not transmitting any data, it is held at a high
voltage level (1).

In order to start the data transfer, the transmitting UART pulls the data line from
high voltage level to low voltage level (from 1 to 0). The receiving UART
detects this change from high to low on the data line and begins reading the
actual data. Usually, there is only one start bit.

Stop Bit: The Stop Bit, as the name suggests, marks the end of the data packet.
It is usually two bits long but often only on bit is used. In order to end the
transmission, the UART maintains the data line at high voltage (1).

Parity Bit: Parity allows the receiver to check whether the received data is
correct or not. Parity is a low – level error checking system and comes in two
varieties: Even Parity and Odd Parity. Parity bit is optional and it is actually not
that widely used.

Data Bits: Data bits are the actual data being transmitted from sender to
receiver. The length of the data frame can be anywhere between 5 and 9 (9 bits
if parity is not used and only 8 bits if parity is used). Usually, the LSB is the
first bit of data to be transmitted (unless otherwise specified).

Rules of UART

As mentioned earlier, there is no clock signal in UART and the transmitter and
receiver must agree on some rules of serial communication for error free
transfer of data. The rules include:

 Synchronisation Bits (Start and Stop bits)

 Parity Bit

 Data Bits and

 Baud Rate

We have seen about synchronisation bits, parity bit and data bits. Another
important parameter is the Baud Rate.

Baud Rate: The speed at which the data is transmitted is mentioned using Baud
Rate. Both the transmitting UART and Receiving UART must agree on the
Baud Rate for a successful data transmission.

Baud Rate is measured in bits per second. Some of the standard baud rates are
4800 bps, 9600 bps, 19200 bps, 115200 bps etc. Out of these 9600 bps baud rate
is the most commonly used one.

Let us see an example data frame where two blocks of data i.e. 00101101 and
11010011 must be transmitted. The format of the frame is 9600 8N1 i.e. 9600
bps with 8 bits of data, no parity and 1 stop bit. In this example, we haven’t
used the parity bit.
Advantages of UART

 Requires only two wires for full duplex data transmission (apart from the
power lines).

 No need for clock or any other timing signal.

 Parity bit ensures basic error checking is integrated in to the data packet
frame.

Disadvantages of UART

 Size of the data in the frame is limited.

 Speed for data transfer is less compared to parallel communication.

 Transmitter and receiver must agree to the rules of transmission and


appropriate baud rate must be selected.

Modbus as an “Open Protocol”


Depending on the process automation equipment manufacturer, a very specific
or proprietary language is used or it may be a language that is commonly open
to the industry. It is these open protocols many manufacturers adapt to easily
integrate their products in a market.

An “Open protocol” means the specifications are published and may be used by
anyone freely or by license.
Open protocols are usually backed by a combination of corporations, user
groups, professional societies, and governments. This provides users with a
much wider choice of devices or systems that can be utilized to meet specific
applications.

Advantages of open protocols include support by multiple manufacturers,


software vendors, and install or service organizations, active community groups
for support, the ability to stay current and add capabilities in the future.

One of the most common Automation Communication Protocols of connecting


industrial electronic devices used today is Modbus.

In this article, we will discuss what Modbus communication protocol is and the
types of Modbus communication used in the industry.

What is Modbus?
The Modbus communication protocol is the oldest and by far the most popular
automation protocol in the field of process automation and SCADA
(Supervisory Control and Data Acquisition).

Knowing how to create Modbus based networks is essential for any electrical
technician and engineer working in these occupation fields.

Being able to integrate devices from different manufacturers is a skill that is in


demand and will ultimately make you more valuable and marketable in the
industry.

Modbus is a communications protocol published by Modicon in 1979 for use


with its Programmable Logic Controllers (PLCs). Modicon is now owned
by Schneider Electric.

Modbus provides a common language for devices and equipment to


communicate with one and another.
For example, Modbus enables devices on a system that measures temperature
and humidity connected on the same network to communicate the results to a
supervisory computer or PLC.
The development and update of Modbus protocols have been managed by
the Modbus Organization. The Modbus Organization is an association of users
and suppliers of Modbus-compliant devices.

Types of Modbus Communication Protocol

Several versions of the Modbus protocol exist for the serial port and Ethernet
and the most common are:
– Modbus RTU
– Modbus ASCII
– Modbus TCP
– Modbus Plus
Modicon published the Modbus communication interface for a multidrop
network based on a Master-Slave architecture.

Communication between the Modbus nodes is achieved with send request and
read response type messages.

Modbus Protocol and its Physical Media

Modbus is an open standard that describes the messaging communication


dialog.
Modbus communicates over several types of physical media such as:
– Serial RS-232
– Serial RS-485
– Serial RS-422
– Ethernet

The original Modbus interface ran on RS-232 serial communication, but most of
the later Modbus implementations use RS-485 because it allowed:
– Longer distances.
– Higher speeds.
– The possibility of multiple devices on a single multi-drop network.
Master-Slave Modbus communication over serial RS-485 physical media using
two-wire transmit and receive connections.

On simple interfaces like RS232 or RS485, the Modbus messages are sent in
plain form over the network and the network will be dedicated to only Modbus
communication.

However, if your network requires multiple heterogeneous devices using a more


versatile network system like TCP/IP over Ethernet, the Modbus messages are
embedded in Ethernet packets with the format prescribed for this physical
interface.

So in this case, Modbus and other types of mixed protocols can co-exist at the
same physical interface at the same time.
Introduction to Modbus Message Structure

The main Modbus message structure is Peer-to-Peer. Modbus is able to function


on both Point-to-Point and Multidrop networks.

Modbus devices communicate using a Master-Slave (Client-Server for Ethernet)


technique in which only one device (the Master/Server) can initiate transactions
(called queries).

The other devices (Slaves/Clients) respond by supplying the requested data to


the master, or by taking the action requested in the query.

A slave is any peripheral device such as an I/O transducer, valve, network drive,
or other measuring types of devices which processes information and sends its
response message to the master using Modbus.
Masters can address individual slaves or initiate a broadcast message to all
slaves. Slaves return a response to all message queries addressed to them
individually, but do not respond to broadcast messages.

Slaves do not initiate messages on their own and only respond to message
queries transmitted from the master.

The master’s query will consist of:


– Slave address (broadcast address).
– Function code with a read or write data command to the slave.
– The write command “Data” if a write command was initiated by the master.
– Error checking field.

The error checking is a value the master or slave creates at the beginning of the
transmission or response and then checked when the message is received to
verify the contents are correct.
A slave’s response consists of:
– Fields confirming it received the request.
– The data to be returned.
– Error checking data.

If no error occurs, the slave’s response contains the data as requested.


If an error occurs in the message query received by the slave, or if the slave is
unable to perform the action requested, the slave will return an exception
message as its response.

The error check field of the slave’s message frame allows the master to confirm
that the contents of the message are valid.
In this article, you learned about what Modbus communication protocol is and
the types of Modbus communication used in the industry.

ASCII Mode
When controllers are setup to communicate on a Modbus network using ASCII
(American Standard Code for Information Interchange) mode, each eight-bit
byte in a message is sent as two ASCII characters. The main advantage of this
mode is that it allows time intervals of up to one second to occur between
characters without causing an error.

Coding System
Hexadecimal ASCII printable characters 0 ... 9, A ... F
Bits per Byte
1 start bit
7 data bits, least significant bit sent first
1 bit for even / odd parity-no bit for no parity
1 stop bit if parity is used-2 bits if no parity
Error Checking
Longitudinal Redundancy Check (LRC)

RTU Mode

When controllers are setup to communicate on a Modbus network using RTU


(Remote Terminal Unit) mode, each eight-bit byte in a message contains two
four-bit hexadecimal characters. The main advantage of this mode is that its
greater character density allows better data throughput than ASCII for the same
baud rate. Each message must be transmitted in a continuous stream.

Coding System
Eight-bit binary, hexadecimal 0 ... 9, A ... F
Two hexadecimal characters contained in each eight-bit field of the message
Bits per Byte
1 start bit
8 data bits, least significant bit sent first
1 bit for even / odd parity-no bit for no parity
1 stop bit if parity is used-2 bits if no parity
Error Check Field
Cyclical Redundancy Check (CRC)

In ASCII mode, messages start with a colon ( : ) character (ASCII 3A hex), and
end with a carriage return-line feed (CRLF) pair (ASCII 0D and 0A hex).
The allowable characters transmitted for all other fields are hexadecimal 0 ... 9,
A ... F. Networked devices monitor the network bus continuously for the colon
character. When one is received, each device decodes the next field (the address
field) to find out if it is the addressed device.
Intervals of up to one second can elapse between characters within the message.
If a greater interval occurs, the receiving device assumes an error has occurred.
A typical message frame is shown below.

Start Address Function Data LRC End

: 2 Chars 2 Chars N Chars 2 Chars CR LF

RTU Framing
In RTU mode, messages start with a silent interval of at least 3.5 character
times. This is most easily implemented as a multiple of character times at the
baud rate that is being used on the network (shown as T1-T2-T3-T4 in the
figure below). The first field then transmitted is the device address.
The allowable characters transmitted for all fields are hexadecimal 0 ... 9, A ...
F. Networked devices monitor the network bus continuously, including during
the silent intervals. When the first field (the address field) is received, each
device decodes it to find out if it is the addressed device.
Following the last transmitted character, a similar interval of at least 3.5
character times marks the end of the message. A new message can begin after
this interval.
The entire message frame must be transmitted as a continuous stream. If a silent
interval of more than 1.5 character times occurs before completion of the frame,
the receiving device flushes the incomplete message and assumes that the next
byte will be the address field of a new message.
Similarly, if a new message begins earlier than 3.5 character times following a
previous message, the receiving device will consider it a continuation of the
previous message. This will set an error, as the value in the final CRC field will
not be valid for the combined messages. A typical message frame is shown
below.

Start Address Function Data CRC End

3.5 Char 3.5 Char


8 Bit 8 Bit N * 8Bit 16 Bit
time time

Address Field
The address field of a message frame contains two characters (ASCII) or eight
bits (RTU). The individual slave devices are assigned addresses in the range of
1 ... 247.

Function Field

The Function Code field tells the addressed slave what function to perform.
The following functions are supported by Modbus poll

01 READ COIL STATUS


02 READ INPUT STATUS
03 READ HOLDING REGISTERS
04 READ INPUT REGISTERS
05 WRITE SINGLE COIL
06 WRITE SINGLE REGISTER
15 WRITE MULTIPLE COILS
16 WRITE MULTIPLE REGISTERS

The data field contains the requested or send data.

Contents of the Error Checking Field


Two kinds of error-checking methods are used for standard Modbus networks.
The error checking field contents depend upon the method that is being used.

Modbus RTU

When controllers are setup to communicate on a Modbus network using


RTU mode, each 8 bit in a message contains two 4–bit hexadecimal
characters.

The main advantage of this mode is that its greater character density allows
better data throughput than ASCII mode for the same baud rate. Each message
must be transmitted in a continuous stream.

MODBUS frame description

The MODBUS application protocol defines a simple Protocol Data Unit (PDU)
independent of the underlying communication layers.

Figure 1 - MODBUS Protocol Data Unit

The mapping of MODBUS protocol on a specific bus or network introduces


some additional fields on the Protocol Data Unit. The client that initiates a
MODBUS transaction builds the MODBUS PDU, and then adds fields in order
to build the appropriate communication PDU.
Figure 2 - MODBUS frame over serial line (see how CRC is calculated)

The valid slave nodes addresses are in the range of 0 – 247 decimal. The
individual slave devices are assigned addresses in the range of 1 – 247. A
master addresses a slave by placing the slave address in the address field of the
message. When the slave returns its response, it places its own address in the
response address field to let the master know which slave is responding. On
MODBUS Serial Line, the Address field only contains the slave address.

The function code indicates to the server what kind of action to perform. The
function code can be followed by a data field that contains request and response
parameters.

Error checking field is the result of a Redundancy Checking calculation that is


performed on the message contents. Two kinds of calculation methods are used
depending on the transmission mode that is being used (RTU or ASCII).

The format (11 bits) for each byte in RTU mode

Coding 8–bit binary, hexadecimal 0–9, A–F


System: Two hexadecimal characters contained in each 8–bit field of
the message.

Bits per Byte: 1 start bit

8 data bits, least significant bit sent first

1 bit for even/odd parity, no bit for no parity

1 stop bit if parity is used, 2 bits if no parity


Even parity is required, other modes (odd parity, no parity) may also be used. In
order to ensure a maximum compatibility with other products, it is
recommended to support also No parity mode. The default parity mode must be
even parity.

How characters are transmitted serially

When messages are transmitted on standard Modbus serial networks, each


character or byte is sent in this order (left to right):
Least Significant Bit (LSB) . . . Most Significant Bit (MSB)

Figure 3 - Bit sequence in RTU mode

Devices may accept by configuration either Even, Odd, or No Parity checking.


If No Parity is implemented, an additional stop bit is transmitted to fill out the
character frame to a full 11-bit asynchronous character.

Frame RTU description

Figure 4 - RTU message frame

The maximum size of a MODBUS RTU frame is 256 bytes.

MODBUS message RTU framing


A MODBUS message is placed by the transmitting device into a frame that has
a known beginning and ending point. This allows devices that receive a new
frame to begin at the start of the message, and to know when the message is
completed. Partial messages must be detected and errors must be set as a result.
In RTU mode, message frames are separated by a silent interval of at least 3.5
character times. In the following sections, this time interval is called t3,5.

Figure 4 - RTU message frame white Start, Stop characters

The entire message frame must be transmitted as a continuous stream of


characters. If a silent interval of more than 1.5 character times occurs between
two characters, the message frame is declared incomplete and should be
discarded by the receiver.

Figure 5 - RTU message frames

Modbus states that a baud rate higher than 19200 must use a fixed 750 us for
inter character time out and 1.75 ms for a frame delay. For baud rates below
19200 the timeing is more critical and has to be calculated. For example 9600
baud in a 10 bit packet is 960 characters per second In milliseconds this will be
960characters per 1000ms. So for 1 character 1000ms/960characters is
1.04167ms per character and finaly modbus states an intercharacter must be
1.5T or 1.5 times longer than a normal character and thus 1.5T = 1.04167ms *
1.5 = 1.5625ms. A frame delay is 3.5T.

The following drawing provides a description of the RTU transmission mode


state diagram. Both "master" and "slave" points of view are expressed in the
same drawing.

Figure 6 - RTU transmission mode state diagram

Some explanations about the above state diagram:

 Transition from 'Initial State' to 'Idle' state needs t3.5 time-out expiration :
that insures inter-frame delay

 'Idle' state is the normal state when neither emission nor reception is
active.

 In RTU mode, the communication link is declared in 'idle' state when


there is no transmission activity after a time interval equal to at least 3,5
characters.

 When the link is in idle state, each transmitted character detected on the
link is identified as the start of a frame. The link goes to the 'active' state.
Then, the end of frame is identified when no more character is
transmitted on the link after the time interval t3,5.
 After detection of the end of frame, the CRC-16 calculation and checking
is completed. Afterwards the address field is analysed to determine if the
frame is for the device. If not the frame is discarded. In order to reduce
the reception processing time the address field can be analysed as soon as
it is received without waiting the end of frame. In this case the CRC will
be calculated and checked only if the frame is addressed to the slave
(broadcast frame included).

Parity checking

Users may configure devices for Even (required) or Odd Parity checking, or for
No Parity checking (recommended). This will determine how the parity bit will
be set in each character.
If either Even or Odd Parity is specified, the quantity of 1 bits will be counted in
the data portion of each character (7 data bits for ASCII mode, or 8 for RTU).
The parity bit will then be set to a 0 or 1 to result in an Even or Odd total of 1
bits.
For example, these 8 data bits are contained in an RTU character frame:
1010 1001

The total quantity of 1 bits in the frame is four. If Even Parity is used, the
frame’s parity bit will be a 0, making the total quantity of 1 bits still an even
number (four).
If Odd Parity is used, the parity bit will be a 1, making an odd quantity (five).
When the message is transmitted, the parity bit is calculated and applied to the
frame of each character. The device that receives counts the quantity of 1 bits
and sets an error if they are not the same as configured for that device (all
devices on the MODBUS Serial Line must be configured to use the same parity
checking method).

Note that parity checking can only detect an error if an odd number of bits are
picked up or dropped in a character frame during transmission. For example, if
Odd Parity checking is employed, and two 1 bits are dropped from a character
containing three 1 bits, the result is still an odd count of 1 bits.
If No Parity checking is specified, no parity bit is transmitted and no parity
checking can be made. An additional stop bit is transmitted to fill out the
character frame.

Frame checking field: 16 bit Cyclical Redundancy Checking (CRC-16)

RTU mode includes an error–checking field which is based on a Cyclical


Redundancy Checking (CRC-16) method performed on the message contents.
The CRC field checks the contents of the entire message. It is applied regardless
of any parity checking method used for the individual characters of the
message.
The CRC field contains a 16–bit value implemented as two 8–bit bytes. The
CRC field is appended to the message as the last field in the message. When this
is done, the low–order byte of the field is appended first, followed by the high–
order byte. The CRC high–order byte is the last byte to be sent in the message.
The CRC value is calculated by the sending device, which appends the CRC to
the message. The receiving device recalculates a CRC during receipt of the
message, and compares the calculated value to the actual value it received in the
CRC field. If the two values are not equal, an error results.

The CRC calculation is started by first pre-loading a 16–bit register to all 1’s.
Then a process begins of applying successive 8–bit bytes of the message to the
current contents of the register. Only the eight bits of data in each character are
used for generating the CRC. Start and stop bits and the parity bit, do not apply
to the CRC.
During generation of the CRC, each 8–bit character is exclusive ORed with the
register contents. Then the result is shifted in the direction of the least
significant bit (LSB), with a zero filled into the most significant bit (MSB)
position. The LSB is extracted and examined. If the LSB was a 1, the register is
then exclusive ORed with a preset, fixed value. If the LSB was a 0, no exclusive
OR takes place.
This process is repeated until eight shifts have been performed. After the last
(eight) shift, the next 8–bit byte is exclusive ORed with the register’s current
value, and the process repeats for eight more shifts as described above. The
final content of the register, after all the bytes of the message have been applied,
is the CRC value. When the CRC is appended to the message, the low-order
byte is appended first, followed by the high-order byte.

Error checking methods

The security of standard MODBUS serial line is based on two kinds of error
checking:

 Parity checking (even or odd) should be applied to each character.

 Frame checking (LRC for ASCII frames or CRC for RTU frames)


must be applied to the entire message.

Both the character checking and message frame checking are generated in the
device (master or slave) that emits and applied to the message contents before
transmission. The device (slave or master) checks each character and the entire
message frame during receipt.

The master is configured by the user to wait for a predetermined timeout


interval ( Response time-out) before aborting the transaction. This interval is set
to be long enough for any slave to respond normally ( unicast request). If the
slave detects a transmission error, the message will not be acted upon. The slave
will not construct a response to the master. Thus the timeout will expire and
allow the master’s program to handle the error. Note that a message addressed
to a nonexistent slave device will also cause a timeout.

Example Modbus RTU frame

Here is an example of a Modbus RTU request for the content of analog output
holding registers #40108 to #40110 from the slave device with address 21.
15 03 00 6B 00 03 77 03

15: The SlaveID address (21 = 0x15)


03: The function code (read analog output holding registers)
006B: The data address of the first register requested (40108 - 40001 offset
= 107 = 0x6B).
0003: The total number of registers requested. (read 3 registers 40108 to
40110)
7703: The CRC (cyclic redundancy check) for error checking.

You might also like