05 Communication Protocol

Download as pdf or txt
Download as pdf or txt
You are on page 1of 88

Communication Protocol

</ENT269>
Objectives
• Upon completion of this chapter, you will
be able to:
– Explain serial communication protocol
– Describe the serial communication features of
the PIC18
– Program the PIC18 serial port in C
What is a communication
protocol?
“A set of formal rules describing how to exchange data.”

“Low-level protocols define the electrical and physical


standards to be observed, bit- and byte-ordering and the
transmission and error detection and correction of the bit
stream.”

“High-level protocols deal with the data formatting, including


the syntax of messages, the terminal to computer dialogue,
character sets, sequencing of messages etc.”
Introduction

Embedded electronics is all about interlinking circuits


(processors or other integrated circuits) to create a
symbiotic system.

In order for those individual circuits to swap their


information, they must share a common communication
protocol.

Hundreds of communication protocols have been defined


to achieve this data exchange, and, in general, each can
be separated into one of two categories: parallel or serial.
Parallel vs. Serial

Parallel interfaces transfer multiple


bits at the same time. They usually
require buses of data -
transmitting across eight, sixteen,
or more wires. Data is transferred
in huge, crashing waves of 1’s and
0’s.

An 8-bit data bus, controlled by a clock,


transmitting a byte every clock pulse. 9
wires are used.
Parallel vs. Serial

Serial interfaces stream their data, one single bit at a time.


These interfaces can operate on as little as one wire,
usually never more than four.

Example of a serial interface, transmitting one bit every clock pulse. Just 2 wires
required!
Basics of Serial Communication
• Asynchronous
• Synchronous

Serial versus Parallel Data Transfer


Asynchronous vs. Synchronous
A synchronous serial interface always pairs its data line(s)
with a clock signal, so all devices on a synchronous serial bus
share a common clock. This makes for a more straightforward,
often faster serial transfer, but it also requires at least one extra
wire between communicating devices. Examples of
synchronous interfaces include SPI, and I2C.

Asynchronous means that data is transferred without


support from an external clock signal. This transmission
method is perfect for minimizing the required wires and I/O
pins, but it does mean we need to put some extra effort into
reliably transferring and receiving data. Example of
asynchronous is UART.
Basics of Serial Communication
Protocol
In Embedded systems, various type of protocol are
available and used according to application

Wired protocols:
SPI, I2C, CAN, UART(RS232, RS485), CAN, USB,
1-wire

Wireless protocols:
Zigbee, Bluetooth, RFID, LoRa, IoT (MQTT, HTTP,
CoAP), NFC
Wired Protocol
I2C - Inter-integrated Circuit: For on chip board communication between
ICs and micro controller, suitable for short distance communication on the
PCB circuit board.

SPI - Serial Peripheral Interface: Most relevant protocol for high speed
communication , For example SD card in mobile makes use of SPI for high
speed data transfer.

UART - Universal Asynchronous Receiver-Transmitter: Asynchronous


serial communication preferred for communication between two devices.
RS232 and RS485 are the preferred ones.

CAN - Controller Area Network: For Automobile communication

USB – Universal Serial Bus: for device storage applications

1-Wire - Similar to I2C but faster when compared to I2C.


Wireless Protocol
Zigbee - is an IEEE 802.15.4-based specification for a suite of high-level
communication protocols used to create personal area networks with small,
low-power digital radios, such as for home automation, medical device data
collection, and other low-power low-bandwidth needs.

Bluetooth - is a wireless technology standard for exchanging data over short


distances (using short-wavelength UHF radio waves in the ISM band from 2.4
to 2.485 GHz) from fixed and mobile devices, and building personal area
networks (PANs).

Radio-frequency identification (RFID) - uses electromagnetic fields to


automatically identify and track tags attached to objects. The tags contain
electronically stored information. Passive tags collect energy from a nearby
RFID reader's interrogating radio waves. Active tags have a local power
source (such as a battery) and may operate hundreds of meters from the
RFID reader. Unlike a barcode, the tag need not be within the line of sight of
the reader, so it may be embedded in the tracked object.
Wireless Protocol
LoRa® - is the physical layer or the wireless modulation utilized to create
the long range communication link. Many legacy wireless systems use
frequency shifting keying (FSK) modulation as the physical layer because it
is a very efficient modulation for achieving low power. LoRa® is based on
chirp spread spectrum modulation, which maintains the same low power
characteristics as FSK modulation but significantly increases the
communication range.

Near-field communication (NFC) - is a set of communication protocols


that enable two electronic devices, one of which is usually a portable device
such as a smartphone, to establish communication by bringing them within
4 cm (1.6 in) of each other.
Wireless Protocol (IoT)
Message Queue Telemetry Transport (MQTT) - Publish-subscribe-based
"lightweight" messaging protocol,for use on top of the TCP/IP protocol.

Constrained Application Protocol (CoAP) - A specialized web transfer


protocol for use with constrained nodes and constrained networks in the
Internet of Things.

Hypertext Transfer Protocol (HTTP) - is an application protocol for


distributed, collaborative, and hypermedia information systems. HTTP is
the foundation of data communication for the World Wide Web. Hypertext
is structured text that uses logical links (hyperlinks) between nodes
containing text. HTTP is the protocol to exchange or transfer hypertext.
Serial Peripheral Interface (SPI)
Serial Peripheral Interface (SPI) is an interface bus commonly used to send data
between microcontrollers and small peripherals such as shift registers, sensors, and
SD cards. It uses separate clock and data lines, along with a select line to choose
the device you wish to talk to.

SPI used mainly for data communication at short distance but with high speed. It is
a synchronous serial communication link.

As shown in the figure one slave is connected with one master device. Clock is
generated by master device for synchronization of data transfer. It is also possible
to connected more than one slave device with single master for communication. SPI
interface operates in either half or full duplex mode.
SPI (Multiple Slaves)
1
- Need a separate SS line.
- To talk to a particular slave, you’ll
make that slave’s SS line low and
keep the rest of them high

- Use a daisy-chained method.


2 - The MISO (output) of one going to
the MOSI (input) of the next. In this
case, a single SS line goes to all
the slaves. Once all the data is
sent, the SS line is raised, which
causes all the chips to be activated
simultaneously.
Inter-integrated Circuit (I2C)
The Inter-integrated Circuit (I2C) Protocol is a protocol intended to allow multiple
“slave” digital integrated circuits (“chips”) to communicate with one or more “master”
chips.

I2C requires a mere two wires, like asynchronous serial, but those two wires can
support up to 1008 slave devices. Also, unlike SPI, I2C can support a multi-master
system, allowing more than one master to communicate with all devices on the bus
(although the master devices can’t talk to each other over the bus and must take turns
using the bus lines).
1-wire
1-Wire is a device communications bus system designed by Dallas
Semiconductor Corp. that provides low-speed data, signaling, and power
over a single conductor. 1-Wire is similar in concept to I2C, but with lower
data rates and longer range. It is typically used to communicate with small
inexpensive devices.
Universal
Asynchronous
Receiver-Transmitter
(UART)
UART
Rules of Serial:

The asynchronous serial protocol has a number of built-in rules-


mechanisms that help ensure robust and error-free data transfers.
These mechanisms, which we get for eschewing the external clock
signal, are:
- Data bits
- Synchronization bits
- Parity bits
- Baud rate.
Through the variety of these signaling mechanisms, you’ll find that
there’s no one way to send data serially. The protocol is highly
configurable. The critical part is making sure that both devices on a
serial bus are configured to use the exact same protocols.
Application: GPS module, Bluetooth, XBee’s, serial LCDs
Baud Rate
The baud rate specifies how fast data is sent over a serial line. It’s usually
expressed in units of bits-per-second (bps). If you invert the baud rate, you
can find out just how long it takes to transmit a single bit. This value
determines how long the transmitter holds a serial line high/low or at what
period the receiving device samples its line.

Baud rates can be just about any value within reason. The only
requirement is that both devices operate at the same rate. One of the more
common baud rates, especially for simple stuff where speed isn’t critical, is
9600 bps. Other “standard” baud are 1200, 2400, 4800, 19200, 38400,
57600, and 115200.

The higher a baud rate goes, the faster data is sent/received, but there are
limits to how fast data can be transferred. You usually won’t see speeds
exceeding 115200 - that’s fast for most microcontrollers. Get too high, and
you’ll begin to see errors on the receiving end, as clocks and sampling
periods just can’t keep up.
Framing the data
Each block (usually a byte) of data transmitted is actually sent in a packet
or frame of bits. Frames are created by appending synchronization and
parity bits to our data.

A serial frame

The real ‘meat’ of every serial packet is the data it carries. The amount of
data in each packet can be set to anything from 5 to 9 bits. Certainly, the
standard data size is your basic 8-bit byte, but other sizes have their
uses.

After agreeing on a character-length, both serial devices also have to


agree on the endianness of their data. Is data sent most-significant bit
(MSB) to least, or vice-versa? If it’s not otherwise stated, you can usually
assume that data is transferred least-significant bit (LSB) first.
Framing the data

The synchronization bits are two or three special bits transferred with
each chunk of data. They are the start bit and the stop bit(s). True to their
name, these bits mark the beginning and end of a packet. There’s always
only one start bit, but the number of stop bits is configurable to either one or
two (though it’s commonly left at one). The start bit is always indicated by an
idle data line going from 1 to 0, while the stop bit(s) will transition back to the
idle state by holding the line at 1.

Parity bits is a form of very simple, low-level error checking. It comes in


two flavors: odd or even. To produce the parity bit, all 5-9 bits of the data
byte are added up, and the evenness of the sum decides whether the bit
is set or not. Parity is optional, and not very widely used.
Example
9600 8N1 - 9600 baud, 8 data bits, no parity, and 1 stop bit - is one of
the more commonly used serial protocols. So, what would a packet or
two of 9600 8N1 data look like? Let’s have an example!
O K

A device transmitting the ASCII characters ‘O’ and ‘K’ would have to
create two packets of data. The ASCII value of O (that’s uppercase) is 79,
which breaks down into an 8-bit binary value of 01001111, while K’s
binary value is 01001011. All that’s left is appending sync bits.
It isn’t specifically stated, but it’s assumed that data is transferred least-
significant bit first. Notice how each of the two bytes is sent as it reads
from right-to-left.

Since we’re transferring at 9600 bps, the time spent holding each of those
bits high or low is 1/(9600 bps) or 104 µs per bit.

For every byte of data transmitted, there are actually 10 bits being sent: a
start bit, 8 data bits, and a stop bit. So, at 9600 bps, we’re actually
sending 9600 bits per second or 960 (9600/10) bytes per second.
Example

Framing ASCII ‘A’ (41H)


Hardware Wiring
A serial bus consists of just two
wires - one for sending data and
another for receiving. As such,
serial devices should have two
serial pins: the receiver, RX,
and the transmitter, TX.

It’s important to note that those RX and TX labels are with


respect to the device itself. So the RX from one device
should go to the TX of the other, and vice-versa. The
transmitter should be talking to the receiver, not to another
transmitter.
Hardware Implementation
RS232 Connector

DB-25
25-Pin Connector

DB-9
9-Pin Connector
RS-232 Standards
• Standard for serial comm (COM port)
1: -3V to -25V;
0: +3V to +25V
– Reason: for long distance wired line

• Connectors
– Minimally, 3 wires: RxD, TxD, GND
– Could have 9-pin or 25-pin

• Standard baud rates:


– 1200, 2400, 4800, 9600, 14.4k, 19.2k, 28.8k..
RS232 Connector (cont’d)

IBM PC DB-9 Signals

Data in Data out Pin 1 – Data Carrier Detect (DCD)


Pin 2 – Received Data (RxD)
Pin 3 – Transmitted Data (TxD)
Pin 4 – Data Terminal Ready (DTR)
Pin 5 – Signal Ground (GND)
Pin 6 – Data Set Ready (/DSR)
Pin 7 – Request to Send (/RTS)
Pin 8 – Clear to Send (/CTS)
Pin 9 – Ring Indicator (RI)
DB-9
9-Pin Connector
Hardware Implementation
Microcontroller

Personal
Computer
PIC18 Connection to RS232

(a) Inside MAX232 (b) its Connection to the PIC18


PIC18 Connection to RS232
(cont’d)

(a) Inside MAX233 (b) Its Connection to the PIC18


But….
Classically, the most serial interface from a microcontroller
to a computer is done through serial port (DB9).

However, since computer serial port used RS232 protocol


and microcontroller used TTL UART, a level shifter is
needed between these interfaces.

Recently, the serial port of computer have been phasing


out, it has been replaced with USB. Of course, the most
developer chooses USB to serial converter to obtain virtual
serial port. The level shifter is still necessary for UART
interface.
Hardware Interfacing (using
USB)
Personal
Computer

Microcontroller
UART Interfacing/Application
Selecting Baud Rates
• Baud rate in PIC18 is SPBRG
programmable Baud Rate
(Hex Value)
• The value loaded into
38400 3
the SPBRG decides
the baud rate 19200 7
9600 F
4800 20
2400 40
1200 81
*For XTAL = 10MHz only!
Baud Rate Formula
Desired Baud Rate = Fosc/(64(X+1))

Example: If Fosc = 10 MHz


X = (156250/Desired Baud Rate) - 1
Desired baud rate = 1200, Clock Frequency =
10MHz

X = (156250/1200) – 1
X = 129.21 = 129 = 81H
TXSTA (Transmit Status and
Control Register)
TXSTA (Transmit Status and
Control Register)
RCSTA (Receive Status and
Control Register)
RCSTA (Receive Status and
Control Register)
PIR: Peripheral Interrupt Register 1
Serial
Communication
Interface-Cable
Serial
Communication
Interface-USB
Wireless Devices
Serial
Communication
Interface-Wireless
Example1
Write a C program to transfer the letter ‘G’ serially at 9600,
continuously. Use 8-bit data and 1 stop bit. Assume XTAL = 10MHz.
Example 1 (cont’d)
Example2
Write a C program to transfer the message “YES” serially at 9600,
continuously. Use 8-bit data and 1 stop bit. Assume XTAL = 10MHz.
Example2 (cont’d)
Example 3
Write a C program to receive bytes of data serially and put them on
PORTB. Set the baud rate at 9600, 8-bit data and 1 stop bit.
Example 3 (cont’d)
RCSTA = 0x90;
Exercise
Select the suitable SPBRG value and TXSTA configuration for a PIC18
microcontroller to set the baud rate at 9600. Then, sketch a flowchart and
write a C18 program to monitor the status of a PIR sensor as shown in
Figure 2. If the PIR sensor (RC7) is activated, send a message “ALRT” to
the serial port continuously. But if the sensor is not activated, send a
message “SAFE” to the serial port. Assume the crystal oscillator frequency
is 10 MHz.
Solution
Exercise
Back

Back Left 1 Back Right


Write a C18 program to monitor
(smartphone - via Bluetooth) the
2 6 status of PIR System if:

1) Condition 1 – Send ‘Back’


2) Condition 2 – Send ‘Back Left’
3) Condition 3 – Send ‘Front Left’
4) Condition 4 – Send ‘Front’
5) Condition 5 – Send ‘Front Right’
3 5
6) Condition 6 – Send ‘Back Right’
4
Front Left Front Right

Front
Application: PIR
Sensor
1) Camping
2) Home Security
3) Etc…
Internet of things (IoT)

The Internet of things (IoT) is the network of physical devices, vehicles,


home appliances and other items embedded with electronics, software,
sensors, actuators, and connectivity which enables these objects to
connect and exchange data. Each thing is uniquely identifiable through
its embedded computing system but is able to inter-operate within the
existing Internet infrastructure.

"Things", in the IoT sense, can refer to a wide variety of devices such
as heart monitoring implants, biochip transponders on farm animals,
cameras streaming live feeds of wild animals in coastal waters,[12]
automobiles with built-in sensors, DNA analysis devices for
environmental/food/pathogen monitoring,[13] or field operation devices
that assist firefighters in search and rescue operations.
-wikipedia
What is ESP8266
The ESP8266 is a System on a Chip (SoC), manufactured
by the Chinese company Espressif. It consists of a
Tensilica L106 32-bit microcontroller unit (MCU) and a WiFi
transceiver. It has 11 GPIO pins* (General Purpose
Input/Output pins), and an analog input as well. This means
that you can program it like any normal Arduino or other
microcontroller. And on top of that, you get WiFi
communication, so you can use it to connect to your WiFi
network, connect to the Internet, host a web server with
real web pages, let your smartphone connect to it, etc . The
possibilities are endless! It's no wonder that this chip has
become the most popular IOT device available.
Type of
ESP8266
Our Lab ESP8266 (ESP12F)
Main
Technical
Specification
Functional Block Diagram
ESP8266
AT
Instruction
Set
http://room-15.github.io/blog/2015/03/26/esp8266-at-command-reference/
Thingspeak (Cloud)
https://thingspeak.com/
Example
Continuously send “AT\r\n” command to ESP8266 (embedded in
ESP12 board) every 5 second. The ESP8266 should reply “OK”
if everything is good. Otherwise it will reply “ERROR”. If the
reply from ESP8266 is “OK”, you have to toggle RB1; otherwise,
toggle RB2.
Note: \r\n = Carriage Return (CR) + Line Feed (LF) //Used as a new line character in Windows
Schematic:
ESP12F Operating Voltage:
3.3V to 3.6V only!!!

3.3V
5V

PIC Operating Voltage:


5V, so ALL I/O also 5V
Voltage Divider
Voltage Divider

In our case:

R2 = 2kΩ and R1 = 1kΩ and Vin from Port Tx (RC6) ~= 5V


So, Vout = 5(2k/(2k+1k)) = 3.33V
Solution
#include <p18f4580.h>
#include <delays.h>
#include <stdio.h>
#include <stdlib.h>

#pragma config OSC = HS


#pragma config WDT = OFF
#pragma config LVP = OFF

unsigned char AT1_msg[]="AT\r\n";

void hello_esp8266(void);
unsigned char receive_and_check(void);
void delay_in_sec(unsigned char second);
void send(unsigned char *p);
Void main()
{
ADCON0 = 0;
ADCON1 = 0X0F; // All Analog port are Digital
TXSTA = 0x20; //Select low baudrate, 8bit
SPBRG = 32; //9600bps, XTAL = 20Mhz
TRISCbits.TRISC6 = 0; //TX pin
TRISCbits.TRISC7 = 1; //RX pin
TRISBbits.TRISB1 = 0;
TRISBbits.TRISB2 = 0;
TRISBbits.TRISB4 = 0;
TXSTAbits.TXEN = 1; //Transmit enable
RCSTAbits.CREN = 1; //Enable continuous receive
RCSTAbits.SPEN = 1; //Enable serial port
PORTBbits.RB1=0;
PORTBbits.RB2=0;
while(1)
{
hello_esp8266();
delay_in_sec(5);
}
}
//This code used for Received "OK" from ESP8266
void hello_esp8266()
{
while (1)
{
send(AT1_msg);
if (receive_and_check())
{
PORTBbits.RB6=1; //Green LED ON indicates no error
PORTBbits.RB7=0; //Red LED ON indicates error
break;
}
else
{
PORTBbits.RB7=1;
PORTBbits.RB6=0;
}
}
}
// To check either received "OK" or not from ESP8266
unsigned char receive_and_check()
{
unsigned char z;

for (z=0; z<20; z++)


{
while(PIR1bits.RCIF == 0); //Check if message is received?
if (RCREG == 'O') //Check if 'O' is the char. If yes,
break; //proceed to check 'K'. Otherwise ignore
}
while(PIR1bits.RCIF == 0); //Check message is received?
if (RCREG == 'K') //Check if ‘K' is the char
return 1;
return 0;
}
void delay_in_sec(unsigned char second)
{
unsigned char z;
for (z=0; z<(second*10); z++){
Delay10KTCYx(50);
}
}

void send(unsigned char *p)


{
for (; *p!='\0'; ++p){
while(PIR1bits.TXIF == 0); //Check whether TXREG is empty (available)
TXREG = *p;
}
}
Step to Send a Data to Cloud

AT AT+CWMODE AT+CWJAP AT+CIPMUX

API KEYS AT+CIPSEND AT+CIPSTART

DATA
AT Command
Exercise
Write a C program to access ESP8266 using AT
command and send the data to Thingspeak server.
Exercise
By using:

#include <stdio.h>
#include <stdlib.h>

//Random between 0 to 50
x = rand() % 50;
y = rand() % 100;

//Convert data to String


itoa(x,buf1);
itoa(y,buf2);

Write a C program to access


ESP8266 using AT command
and send the data to Thingspeak
server.
IoT Application
“Write to be understood, speak
to be heard, read to grow”

Thank You

You might also like