0% found this document useful (0 votes)
2 views49 pages

UART

The document provides an overview of serial communication, detailing its types, including synchronous and asynchronous transmission, and the specifics of protocols like UART. It explains how data is transmitted and received, error detection methods, and the software structure for handling serial communications. Additionally, it covers the UART's operational parameters and its role in converting data between parallel and serial formats.

Uploaded by

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

UART

The document provides an overview of serial communication, detailing its types, including synchronous and asynchronous transmission, and the specifics of protocols like UART. It explains how data is transmitted and received, error detection methods, and the software structure for handling serial communications. Additionally, it covers the UART's operational parameters and its role in converting data between parallel and serial formats.

Uploaded by

pasqualed70
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Serial Communications

Ing. Gianni Cario


Serial Communication
▪ Serial communication
▪ Transmits data one bit at a time, in a sequential fashion
▪ In contrast to parallel communication, in which multiple bits are sent as a whole at the same time
▪ Commonly used for long-haul communication, modems and non-networked communication between
devices
▪ Example are UART, SPI, I2C, USB, Ethernet PCI Express etc.

1 1
0 0
1 1
1 1
10111001 1
1 0 1 1 1 0 0 1 1 0
0 0
0 1
1
Serial communication Parallel communication
Types of Serial Communication
▪ Synchronous Serial Transmission

➢ A common clock is shared by both the sender and the receiver

➢ More efficient transmission, since one wire is dedicated for data transfer

➢ Costly if an extra clock wire is required

▪ Asynchronous Serial Transmission

➢ The sender does not have to send a clock signal

➢ Both sender and receiver agree on timing parameters in advance

➢ Special bits are added to synchronize transmission


Synchronous Serial Data Transmission
Parallel Data In
D3 D2 D1 D0

Serial Serial
D Q D Q D Q D Q Data In D Q D Q D Q D Q
Data Out

Clk Clk

D3 D2 D1 D0
Parallel Data Out

Transmitting Device Receiving Device


Clock
Serial Data
Data Sampling Time at Receiver

▪ Use shift registers and a clock signal to convert between serial and parallel formats
▪ Synchronous: an explicit clock signal is along with the data signal
Synchronous Full-Duplex Serial Data Bus

Select Select Select Select


Peripheral Peripheral Peripheral Peripheral
Clk DIn DOut DIn DOut DIn DOut DIn DOut
MCU

▪ Now can use two serial data lines - one for reading, one for writing.
▪ Allows simultaneous send and receive full-duplex communication
Synchronous Half-Duplex Serial Data Bus

Select Select Select Select


Peripheral Peripheral Peripheral Peripheral
Clk Data Clk Data Clk Data Clk Data
MCU

▪ Share the serial data line


▪ Doesn’t allow simultaneous send and receive - is half-duplex communication
Asynchronous Serial Communication
Data bits
Start bit Stop bit

Time Zero

Tbit*1.5

Tbit*2.5

Tbit*3.5

Tbit*4.5

Tbit*5.5

Tbit*6.5

Tbit*7.5

Tbit*8.5

Tbit*9.5
Data Sampling
Time at Receiver

▪ Eliminate the clock line!


▪ Transmitter and receiver must generate clock locally
▪ Transmitter must add start bit (always same value) to indicate start of each data frame
▪ Receiver detects leading edge of start bit, then uses it as a timing reference for sampling
data line to extract each data bit N at time Tbit*(N+1.5)
▪ Stop bit is also used to detect some timing errors
Serial Communication Specifics

▪ Data frame fields Start bit Data bits Stop bit


▪ Start bit (one bit)
▪ Data (LSB first or MSB, and
size – 7, 8, 9 bits) Message
▪ Optional parity bit is used to make total number of ones in data even or odd
▪ Stop bit (one or two bits)
▪ All devices must use the same communications parameters
▪ E.g. communication speed (300 baud, 600, 1200, 2400, 9600, 14400, 19200, etc.)
▪ Sophisticated network protocols have more information in each data frame
▪ Medium access control – when multiple nodes are on bus, they must arbitrate for permission to transmit
▪ Addressing information – for which node is this message intended?
▪ Larger data payload
▪ Stronger error detection or error correction information
▪ Request for immediate response (“in-frame”)
Error Detection

▪ Can send additional information to verify data was received correctly


▪ Need to specify which parity to expect: even, odd or none.
▪ Parity bit is set so that total number of “1” bits in data and parity is even (for even
parity) or odd (for odd parity)
▪ 01110111 has 6 “1” bits, so parity bit will be 1 for odd parity, 0 for even parity
▪ 01100111 has 5 “1” bits, so parity bit will be 0 for odd parity, 1 for even parity
▪ Single parity bit detects if 1, 3, 5, 7 or 9 bits are corrupted, but doesn’t detect an even
number of corrupted bits
▪ Stronger error detection codes (e.g. Cyclic Redundancy Check) exist and use multiple
bits (e.g. 8, 16), and can detect many more corruptions.
▪ Used for CAN, USB, Ethernet, Bluetooth, etc.
Software Structure

▪ Communication is asynchronous to program


▪ Don’t know what code the program will be executing …
◦ when the next item arrives
◦ when current outgoing item completes transmission
◦ when an error occurs
▪ Need to synchronize between program and serial communication interface somehow
▪ Options
▪ Polling
◦ Wait until data is available
◦ Simple but inefficient of processor time
▪ Interrupt
◦ CPU interrupts program when data is available
◦ Efficient, but more complex
Serial Communications and Interrupts
Main Program or
other threads
▪ Want to provide multiple threads of control in the
program
send_string get_string
▪ Main program (and subroutines it calls)
▪ Transmit ISR – executes when serial interface is ready to
send another character
▪ Receive ISR – executes when serial interface receives a
character
▪ Error ISR(s) – execute if an error occurs
tx_isr rx_isr

▪ Need a way of buffering information between threads


▪ Solution: circular queue with head and tail pointers Serial
Interface
▪ One for tx, one for rx
Enabling and Connecting Interrupts to ISRs
▪ ARM Cortex-M4 void USART2_IRQHandler(){
provides various IRQs
for all communication if (transmitter ready) {
interface’s events if (more data to send) {
▪ I2C1EVENT get next byte
▪ I2C1ERROR send it out transmitter
▪ I2C2EVENT }
▪ I2C2ERROR }
▪ SPI1 if (received data) {
▪ SPI2 get byte from receiver
▪ USART1 save it
▪ USART2 }
▪ USART3 if (error occurred) {
handle error
▪ Decide which } }
operation to take in
each IRQ
Decoding Messages

▪ Two types of messages


▪ Actual binary data sent
◦ First identify message type
◦ Second, based on this message type, copy binary data from message fields into variables
◦ May need to use pointers and casting to get code to translate formats correctly and safely
▪ ASCII text characters representing data sent
◦ First identify message type
◦ Second, based on this message type, translate (parse) the data from the ASCII message format into a binary
format
◦ Third, copy the binary data into variables
Example Binary Serial Data: TSIP

switch (id) {
case 0x84:
lat = *((double *)(&msg[0]));
lon = *((double *)(&msg[8]));
alt = *((double *)(&msg[16]));
clb = *((double *)(&msg[24]));
tof = *((float *)(&msg[32]));
break; Report Packet (0x84) Data Structure
case 0x4A: … Type sizeof(Type) Item Units
default: Double 8 Latitude Radians; + for
break; north, - for south
} Double 8 Longitude Radians; + for east,
- for west
Double 8 Altitude Meters
Double 8 Clock Bias Meters
Single 4 Time-of-fix Seconds
Example ASCII Serial Data: NMEA-0183

$IDMSG,D1,D2,D3,D4,…,Dn*CS\r\n
▪ $ denotes the start of a message
▪ ID is a two letter mnemonic to describe the source of data,
e.g. GP signifies GPS
▪ MSG is a three letter mnemonic to describe the message
content.
▪ Commas are used to delaminate the data fields.
▪ Dn represents each of the data fields.
▪ * is used to separate the data from the checksum.
▪ CS contains two ASCII characters representing the hex
value of the checksum.
▪ \r\n is the carriage return character followed by the new line
character to denote the end of a message.
State Machine for Parsing NMEA-0183
Any char. except *, \r or \n
Start $ Append char to buf.
Append char to buf. Talker + Inc. counter
*, \r or \n, Sentence
non-text, or Type
buf==$SDDBT, $VWVHW, or $YXXDR
counter>6 Enqueue all chars. from buf

/r or /n
Sentence
Body Any char. except *
Enqueue char
*
Enqueue char

Checksum
1
Any char.
Save as checksum1
Checksum
2
Any char.
Save as checksum2
Universal Asynchronous
Receiver/Transmitter (UART)
UART Overview
▪ Universal Asynchronous Receiver/Transmitter (UART)

▪ Asynchronous communication, no clock wire required, pre-agreed baud rate

▪ Separate transmit and receive wires

▪ UART communication

▪ Converts data from parallel to serial

▪ Sequential data is transferred through serial cable

▪ Receives the sequential data and reassembles it back to parallel

tx rx
device1 device2
rx tx
Transmitter Basics
Data
bits

Data Sampling

Time Zero
Time at Receiver

Tbit
Tbit

Tbit

Tbit

Tbit

Tbit

Tbit

Tbit

Tbit

Tbit

Tbit
▪ If no data to send, keep sending 1 (stop bit) – idle line
▪ When there is a data word to send
▪ Send a 0 (start bit) to indicate the start of a word
▪ Send each data bit in the word (use a shift register for the transmit buffer)
▪ Send a 1 (stop bit) to indicate the end of the word
Receiver Basics
Data
bits

Data Sampling

Zero
Time

Tbit*10.5
Tbit*1.5

Tbit*2.5

Tbit*3.5

Tbit*4.5

Tbit*5.5

Tbit*6.5

Tbit*7.5

Tbit*8.5

Tbit*9.5
Time at
Receiver

▪ Wait for a falling edge (beginning of a Start bit)


▪ Then wait ½ bit time
▪ Do the following for as many data bits in the word
◦ Wait 1 bit time
◦ Read the data bit and shift it into a receive buffer (shift register)

▪ Wait 1 bit time


▪ Read the bit
◦ if 1 (Stop bit), then OK
◦ if 0, there’s a problem!
For this to work…

▪ Transmitter and receiver must agree on several things (protocol)


▪ Order of data bits
▪ Number of data bits
▪ What a start bit is (1 or 0)
▪ What a stop bit is (1 or 0)
▪ How long a bit lasts
◦ Transmitter and receiver clocks must be reasonably close, since the only timing reference is the start of the
start bit
Input Data Oversampling

▪ When receiving, UART oversamples incoming data line


▪ Extra samples allow voting, improving noise immunity
▪ Better synchronization to incoming data, improving noise immunity

▪ Configurable oversampling from 8x to 16x


USART
▪ Like other modules, USART in the STM32F4 families is capable to operate in
many modes.

ARM University Program


Copyright © ARM Ltd 2013 23
2
4

USART Block Diagram


STM32F4
How the STM32F4 works
▪ Transmitter and receiver must agree on several things (protocol)
▪ Order of data bits
▪ LSB will be transmitted first
▪ Number of data bits
▪ Can be configured as 8 or 9 bits
▪ What a start bit is (1 or 0)
▪ 0
▪ What a stop bit is (1 or 0)
▪ 1
▪ Configurable length (0.5, 1, 1.5 or 2)
▪ How long a bit lasts
▪ Software programmable phase and polarity

ARM University Program


Copyright © ARM Ltd 2013 25
UART transmission parameters
The following parameters must be set in the UART hardware:
• transmission speed, in bps = Bit Per Second or baud
• number of bits per character, usually 8
• presence/absence of partity bit, usually absent
• number of stop bits, usually 1
Corrado Santoro

A setting 19200,8,N,1 means:


• speed = 19200 bit-per-second;
• bits = 8;
• parity = None;
• stop bits = 1.
Simplified Schematics of UART

Corrado Santoro Using the UART

TX TX RX
Reg Compl. Not
Empty Empty

Three main blocks:


• Baud Rate Generator
• Transmitter Circuit
• Receiver Circuit
UART—Baud Rate Generation

Corrado Santoro Using the UART

TX TX RX
Reg Compl. Not
Empty Empty

The Baud Rate Generator is responsible of generating the clock for


data transmission
UART—Data Reception

Using the UART

Corrado Santoro Using the UART

TX TX RX
Reg Compl. Not
Empty Empty

▪ The Receiver Circuit is responsible of receiving data bits, checking correctness and
deliver the complete data byte to the software
▪ It has a shift register that gathers one bit at time
▪ When a byte is completed, the content of the shift register is copied into the RX Data
Register and the bit ‘‘RX R e g i s t e r Not Empty’’ is set in the Status Register
UART—Data Transmission (I)

Using the UART

Corrado Santoro Using the UART

TX TX RX
Reg Compl. Not
Empty Empty

▪ The Transmitter Circuit is responsible of trasmitting data bits


▪ Data to be trasmitted is loaded (by the software) into the TX Data Register
▪ The value of TX Data Register is then copied o the TX shift register and the
bit ‘‘TX Register Empty’’ is set in the Status Register
UART—Data Transmission (II)

Using the UART

Corrado Santoro Using the UART

TX TX RX
Reg Compl. Not
Empty Empty

▪ Data in the TX shift register is sent one bit at time


▪ As soon as all the 8 bits are transmitted, the bit ‘‘TX C o m p l e t e ’’ is set in the
Status Register
UART—Status Register

Using the UART

Corrado Santoro Using the UART

TX TX RX
Reg Compl. Not
Empty Empty

▪ Events occurring in the UART (data tramission, data reception, errors) are signaled
by setting proper bits in the Status Register
▪ Each event can be also configured to generate a IRQ
▪ In this way, transmission and reception can be performed with interrupt-driven
routine instead of using the classical polling
USART Control Register 1 (USART_CR1)

▪ OVER8: 0 → oversampling by 16; 1 → oversampling by 8


▪ UE: Write 1 to enable
▪ M: Word length: 0 → 8 data bits; 1 → 9 data bits
▪ WAKE: Wakeup method
▪ PCE: Parity enabled with 1
▪ PS: 1 → Odd parity; 0 → even parity
▪ TE: Transmitter enable
▪ RE: Receiver enable

ARM University Program


Copyright © ARM Ltd 2013 33
USART Control Register 2 and 3 (USART_CR2/3)

▪ STOP: STOP bits:


▪ 00 →1 Stop bit; 01 → 0.5 Stop bit; 10 → 2 Stop bits; 11 → 1.5 Stop bit

▪ DMAT : DMA enable transmitter


▪ DMAR: DMA enable Reciever

ARM University Program


Copyright © ARM Ltd 2013 34
Baud Rate Register (USART_BRR)

▪ DIV_Mantissa[11:0]
▪ Mantissa for the USART Divider
▪ DIV_Fraction[3:0]
▪ Fraction of USART Divider
▪ When OVER8 is set, DIV_Fraction3 bit is not considered and must be
cleared

ARM University Program


Copyright © ARM Ltd 2013 35
Baud Rate

𝑓𝑃𝐶𝐿𝐾
𝐵𝑎𝑢𝑑 𝑅𝑎𝑡𝑒 =
8 × (2 − 𝑂𝑉𝐸𝑅8) × 𝑈𝑆𝐴𝑅𝑇𝐷𝐼𝑉

▪ If OVER8 is 0, then the signal is oversampled by 16, and 4 bits are


used for the fractional part.
▪ If OVER8 is 1, then the signal is oversampled by 8, and 3 bits are
used.
▪ If BRR is 0x1BC and OVER8 is 0, then 0x1B is the integer part
and 0xC is the fractional part.
0𝑥𝐶 12
▪ 𝑈𝑆𝐴𝑅𝑇𝐷𝑉 = 0𝑥1𝐵 + = 27 + = 27.75
0𝑥10 16
Baud Rate
▪ Suppose the processor clock 𝑓𝑃𝐶𝐿𝐾 is 16MHz, and the system is oversampled by 16
(𝑂𝑉𝐸𝑅8 = 0),
𝑓𝑃𝐶𝐿𝐾
▪ 𝑈𝑆𝐴𝑅𝑇𝐷𝐼𝑉 =
8× 2−𝑂𝑉𝐸𝑅8 ×𝐵𝑎𝑢𝑑 𝑅𝑎𝑡𝑒

16 × 106
= = 104.1667
8 × 2 − 0 × 9600

▪ Thus USARTDIV is 104.1875, which is encoded as 0x683.


▪ desired baud rate 9600
16 × 106
𝐵𝑎𝑢𝑑 𝑅𝑎𝑡𝑒 = = 9598
8 × (2 − 0) × 104.1875
Data Register (USART_DR)
▪ DR[8:0]:Data value
▪ The data to be transmitted or the data received, depending on whether it is read
from or written to

▪ The TDR register provides the parallel interface between the internal bus and
the output shift register .
▪ The RDR register provides the parallel interface between the input shift
register and

ARM University Program


Copyright © ARM Ltd 2013 38
UART Status Register (USART_SR)

▪ TXE: Transmit data register empty


▪ TC: Transmission complete.
▪ RXNE: Read data register not empty
▪ IDLE: IDLE line detected
▪ ORE: Receive overrun. Received data has overwritten previous data
in receive buffer
▪ NF: Noise flag. Receiver data bit samples don’t agree.
▪ FE: Framing error. Received 0 for a stop bit, expected 1.
▪ PE: Parity error. Incorrect parity received.

ARM University Program


Copyright © ARM Ltd 2013 39
Using the UART
▪ Transmitter ▪ Receiver
▪ Configure the GPIO ▪ Configure the GPIO
▪ AF mode, fast speed ▪ AF mode, fast speed
▪ Enable the USART (Set UE in CR1) ▪ Enable the USART (Set UE in CR1)
▪ Define word length (writing M bit in CR1) ▪ Define word length (M bit in CR1)
▪ Program the stop bits (CR2) ▪ Program the stop bits (CR2)
▪ Using DMA? (DMAT in CR3) ▪ Using DMA? (DMAR in CR3)
▪ Parity Check? (PCE/PS in CR1) ▪ Parity Check?(PCE/PS in CR1)
▪ Configure Baud Rate (USART_BRR) ▪ Configure Baud Rate (USART_BRR)
▪ First transmission (Set TE in CR1) ▪ Begin waiting for start bit (Set RE in CR1)
▪ Write data to send (DR) ▪ If RXNE is set, then the data has
▪ Repeat writing data to send (DR) been received and can be read
▪ For ending the transmission, wait until ▪ Interrupt if RXNEIE bit is set
the last frame is complete (when
TC=1)

ARM University Program


Copyright © ARM Ltd 2013 40
Software for Polled Serial Comm.
void u s a r t 2 _ i n i t ( ) {
// enable USART2 clock, bit 17 on APB1ENR
RCC->APB1ENR |= (1 << 17);

// enable GPIOA clock, bit 0 on AHB1ENR


RCC->AHB1ENR |= (1 << 0);

// set pin modes as alternate mode 7 (pins 2 and 3)


GPIOA->MODER &= 0xFFFFFF0F;
GPIOA->MODER |= 0x000000A0; // Set pin 2/3 to alternate func. mode (0b10)

// set pin modes as high speed


GPIOA->OSPEEDR |= 0x000000A0; // Set pin 2/3 to high speed mode (0b10)

// choose AF7 for USART2 in Alternate Function registers


GPIOA->AFR[0] |= (0x7 << 8); // for pin 2
GPIOA->AFR[0] |= (0x7 << 12); // for pin 3

// usart2 word length M, bit 12


USART2->CR1 |= (0 << 12); // 0 - 1,8,n

// usart2 parity control, bit 9


USART2->CR1 |= (0 << 9); // 0 - no parity
ARM University Program
Copyright © ARM Ltd 2013 41
Software for Polled Serial Comm.
void u s a r t 2 _ i n i t ( ) {

……
// usart2 tx enable, TE bit 3
USART2->CR1 |= (1 << 3);

// usart2 rx enable, RE bit 2


USART2->CR1 |= (1 << 2);

// baud rate = fCK / (8 * (2 - OVER8) * USARTDIV)


// for fCK = 42 Mhz, baud = 115200, OVER8 = 0
// USARTDIV = 42Mhz / (115200 * 16)
// = 22.7864 → 0.7864*16=12.5824 → nearest integer 13 → 13/16=0.8125
// for 42 Mhz PCLK, OVER8 = 0 and 115.2 KBps baud
// we need to program 22.8125
// Fraction : 16*0.8125 = 13 (multiply fraction with 16)
// Mantissa : 22
// 12-bit mantissa and 4-bit fraction
USART2->BRR |= (22 << 4);
USART2->BRR |= 13;
// enable usart2 - UE, bit 13
USART2->CR1 |= (1 << 13);
}
ARM University Program
Copyright © ARM Ltd 2013 42
Example Transmitter
i n t m a i n ( void) {
char str[] = "embedded\n\r";
usart2_init();

while(1)
{
for (int i=0; i<sizeof(str); i++){
// send character
USART2->DR = str[i];
// wait for transmit complete
while(!(USART2->SR & (1 << 6)));
// slow down
for(int i=0; i<1000000; i++);
}
}

}
ARM University Program
Copyright © ARM Ltd 2013 43
Example Receiver
i n t m a i n ( void) {
char str[10];
usart2_init();

while(1)
{
for (int i=0; i<sizeof(str); i++){
// wait for rx data
while(!(USART2->SR & (1 << 5)));
// save character
str[i] = USART2->DR;

}
}

ARM University Program


Copyright © ARM Ltd 2013 44
Software for Interrupt-Driven Serial Comm.
▪ Use interrupts

▪ First, initialize peripheral to generate interrupts

▪ Second, create single ISR with three sections corresponding to cause


of interrupt
▪ Transmitter
▪ Receiver
▪ Error

ARM University Program


Copyright © ARM Ltd 2013 45
USART Control Register 1 (USART_CR1)

▪ TXEIE: TXE interrupt enable


▪ TCIE: Transmission complete interrupt enable
▪ RXNEIE: RXNE interrupt enable, this means whenever overrun error
or read data register is not empty(ORE=1 or RXNE=1), it will assert
the interrupt.

ARM University Program


Copyright © ARM Ltd 2013 46
Interrupt Initialization(transmitter)
void u s a r t 2 _ i n i t ( ){

NVIC_SetPriority(USART2_IRQn, 0 ) ;
NVIC_ClearPendingIRQ(USART2_IRQn);
NVIC_EnableIRQ(USART2_IRQn);

USART2->CR1 |= (1 << 6);



}

ARM University Program


Copyright © ARM Ltd 2013 47
Interrupt Handler:Transmitter
void USART2_IRQHandler(void)
{
NVIC_ClearPendingIRQ(USART2_IRQn);
// check if the source is transmit interrupt
if (USART2->SR & (1 << 6)) {
// clear interrupt
USART2->SR &= ~(1 << 6);

if (bufpos == sizeof(str)) {
// buffer is flushed out, disable tx interrupt
tx_complete = 1;
USART2->CR1 &=~(1 << 6);
}
else {
// flush ot the next char in the buffer
tx_complete = 0;
USART2->DR = str[bufpos++];
}
}
}
ARM University Program
Copyright © ARM Ltd 2013 48
Interrupt Handler: Receiver
void USART2_IRQHandler(void)
{
NVIC_ClearPendingIRQ(USART2_IRQn);
// check if the source is rx interrupt
if (USART2->SR & (1 << 5)) {
// clear interrupt
USART2->SR &= ~(1 << 5);

}
// check if the source is error interrupt
if (USART2->SR & (1 << 3)) {
// clear interrupt
USART2->SR &= ~(1 << 3);

}

ARM University Program


Copyright © ARM Ltd 2013 49

You might also like