0% found this document useful (0 votes)
59 views47 pages

Proc Embarqué - Ch5

The document discusses general purpose input/output (GPIO) and serial communication, covering GPIO concepts and circuitry, driver layers, interfacing circuits, definitions of serial communication, software for asynchronous communication, UART communication, and comparisons of serial communication protocols. It provides information on configuring and using GPIO pins for inputs, outputs, and alternative functions as well as implementing serial communication using UART.

Uploaded by

test test
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)
59 views47 pages

Proc Embarqué - Ch5

The document discusses general purpose input/output (GPIO) and serial communication, covering GPIO concepts and circuitry, driver layers, interfacing circuits, definitions of serial communication, software for asynchronous communication, UART communication, and comparisons of serial communication protocols. It provides information on configuring and using GPIO pins for inputs, outputs, and alternative functions as well as implementing serial communication using UART.

Uploaded by

test test
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
You are on page 1/ 47

Chapter 5

General Purpose I/O & Serial Communication

1
Chapter Syllabus

▪ GPIO
▪ Basic Concepts & Port Circuitry
▪ Driver Layer
▪ Circuit Interfacing

▪ Serial Communication
▪ Serial Communication Definition
▪ Software Structure for Handling Asynchronous Communication
▪ UART Communication
▪ Serial Communication Protocols Comparison

2
GPIO BASIC CONCEPTS
& PORT CIRCUITRY

3
GPIO Basic Concepts

▪ Goal: light either LED1 or LED2 based on switch SW1 position


▪ GPIO = General-purpose input and output (digital)
▪ Input: program can determine if input signal is a 1 or a 0
▪ Output: program can set output to 1 or 0
▪ Can use this to interface with external devices
▪ Input: switch
▪ Output: LEDs

4
GPIO Alternative Functions

▪ Pins may have different features

▪ To enable an alternative function, set up the Memory Mapped I/O


appropriate register Alternate Function 1
Alternate Function 2 Pin

Alternate Function n
▪ May also have analogue paths for ADC / DAC
etc.
Function Select

▪ Advantages:
▪ Saves space on the package
▪ Improves flexibility

5
Pull-Up & Pull-Down Resistors
Pull-down Pull-up
▪ Ensure a known value on the output if a pin is left
floating

▪ In our example, we want the switch SW1 to pull


the pin to ground, so we enable the pull-up

▪ The pin value is:


▪ High when SW1 is not pressed
▪ Low when SW1 is pressed

6
GPIO DRIVER LAYER

7
Code Structure
▪ Main code talks to the drivers, producing easy to read and
understand code High Level main.c
▪ gpio_set_mode(P2_5, Output)
drivers
▪ Drivers utilise CMSIS library and group relevant actions
▪ port_struct->direction_reg = output
CMSIS
▪ CMSIS transforms memory mapped registers into C structs
▪ #define PORT0 ((struct PORT*)0x2000030)
Registers
▪ Registers directly control hardware Low Level
Input Pin
Output Hardware
direction_reg

▪ Hardware drives IO pins physically

8
GPIO Drivers Layer: How It Works

void gpio_set(Pin pin, int value)


1) mask = 1 << pin.index
2) tmp = pin.port_struct -> data_reg & ~mask
3) tmp |= value << pin.index
4) pin.port_struct -> data_reg = tmp

▪ e.g. gpio_set(P2_5, 1) with PORT_DATA_REGISTER = 0b01010101


1. Create a mask for the bit we want to set (0b00100000)
2. Invert the mask (0b11011111) to select all the other bits in the port data register, and save the status of the
other bits (tmp = 0b01010101)
3. Move the new value of the bit into position, and or it with the new register value (tmp = 0b01110101)
4. Write the new data register value out to the port (PORT_DATA_REGISTER = 0b01110101)

9
GPIO Drivers Layer: How It Works

int gpio_get(Pin pin)


1) mask = 1 << pin.index
2) tmp = pin.port_struct->data_reg & mask
3) tmp >>= pin.index
4) return tmp

▪ e.g. gpio_get(P2_5) with PORT_DATA_REGISTER = 0b01110101


1. Create a mask for the bit we want to get (0b00100000)
2. Select the bit in the port data register based on the mask (tmp = 0b00100000)
3. Bitshift the value to produce a one or zero (tmp = 0b00000001)
4. Return the value of the pin back to the user

10
C Interface: GPIO Configuration

/*! This enum describes the directional setup of a GPIO pin. */


typedef enum {
Reset, //!< Resets the pin-mode to the default value.
Input, //!< Sets the pin as an input with no pull-up or pull-down.
Output, //!< Sets the pin as a low impedance output.
PullUp, //!< Enables the internal pull-up resistor and sets as input.
PullDown //!< Enables the internal pull-down resistor and sets as input.
} PinMode;

/*! \brief Configures the output mode of a GPIO pin.


* Used to set the GPIO as an input, output, and configure the
* possible pull-up or pull-down resistors.
* \param pin Pin to set.
* \param mode New output mode of the pin.
*/
void gpio_set_mode(Pin pin, PinMode mode);

11
C Interface: GPIO Reading and Writing

/*! \brief Sets a pin to the specified logic level.


* \param pin Pin to set.
* \param value New logic level of the pin (0 is low, otherwise high).
*/
void gpio_set(Pin pin, int value);

/*! \brief Get the current logic level of a GPIO pin.


* \param pin Pin to read.
* \return The logic level of the GPIO pin (0 if low, 1 if high).
*/
int gpio_get(Pin pin);

12
Pseudocode for Program

Make LED1 and LED2 outputs


Make switch an input with a pull-up resistor
do forever {
if switch is not pressed {
Turn off LED1
Turn on LED2
} else {
Turn off LED2
Turn on LED1
}
}

13
C Code

gpio_set_mode(P_LED1, Output); // Set LED pins to outputs


gpio_set_mode(P_LED2, Output);
gpio_set_mode(P_SW, Pullup); // Switch pin to resistive pull-up

while (1) {
if (gpio_get(P_SW)) {
// Switch is not pressed (active low), turn LED1 off and LED2 on.
gpio_set(P_LED1, 0);
gpio_set(P_LED2, 1);
} else {
// Switch is pressed, turn LED2 off and LED1 on.
gpio_set(P_LED2, 0);
gpio_set(P_LED1, 1);
}
}

14
Inputs and Outputs, Ones and Zeros,Voltages and Currents

INTERFACING

15
Inputs: What’s a One? A Zero?

▪ Input signal’s value is determined by voltage

▪ Input threshold voltages depend on supply


voltage VDD

▪ Exceeding VDD or GND may damage chip

16
Outputs: What’s a One? A Zero?

▪ Nominal output voltages


▪ 1: VDD-0.5 V to VDD
▪ 0: 0 to 0.5 V

▪ Note: Output voltage depends on current drawn


by load on pin
Logic 1 out
▪ Need to consider source-to-drain resistance in the
transistor
▪ Above values only specified when current < 5 mA

Vout
(18 mA for high-drive pads) and VDD > 2.7 V

Logic 0 out

Iout
17
Output Example: Driving LEDs

▪ Need to limit current to a value which is safe for


both LED and MCU port driver
▪ Use current-limiting resistor
▪ R = (VDD – VLED)/ILED
▪ Set ILED = 4 mA
▪ VLED depends on type of LED (mainly color)
▪ Red: ~1.8V
▪ Blue: ~2.7 V
▪ Solve for R given VDD = ~3.0 V
▪ Red: 300 Ω
▪ Blue: 75 Ω

18
Output Example: Driving a Speaker

▪ Create a square wave with a GPIO output


▪ Use capacitor to block DC value
▪ Use resistor to reduce volume if needed

void beep(void) {
unsigned int period = 20;
while (1) {
gpio_toggle(P_SPEAKER);
delay_ms(period/2);
}
}

19
Serial Communications

20
SERIAL COMMUNICATION
DEFINITION

21
Why Communicate Serially?

▪ Native word size is multi-bit (8, 16, 32, etc.)

▪ Often it’s not feasible to support sending all the word’s bits at the same time
▪ Cost and weight: more wires needed, larger connectors needed
▪ Mechanical reliability: more wires => more connector contacts to fail
▪ Timing Complexity: some bits may arrive later than others due to variations in capacitance and
resistance across conductors
▪ Circuit complexity and power: may not want to have 16 different radio transmitters + receivers in the
system

Select Select Select Select


Peripheral Peripheral Peripheral Peripheral
Wr Rd Data Wr Rd Data Wr Rd Data Wr Rd Data
MCU

22
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

23
Synchronous Serial Data Bus Configurations

Select Select Select Select


Peripheral Peripheral Peripheral Peripheral
Clk DIn DOut DIn DOut DIn DOut DIn DOut
Full Duplex Bus MCU

▪ Use of two serial data lines - one for reading, one for writing. Allows simultaneous send and
receive full-duplex communication

Select Select Select Select


Peripheral Peripheral Peripheral Peripheral
Clk Data Clk Data Clk Data Clk Data

Half Duplex Bus MCU

▪ Share the serial data line. Doesn’t allow simultaneous send and receive
24
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
25
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”)
26
Error Detection

▪ Can send additional information to verify data was received correctly


▪ Need to specify which parity to expect: even or odd
▪ 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 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.

27
SOFTWARE STRUCTURE – HANDLING
ASYNCHRONOUS COMMUNICATION

28
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

29
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

30
Code to Implement Queues
older newer
data
▪ Enqueue at tail: tail is the index of the next free entry data
▪ Dequeue from head: head is the index of the item to remove
▪ Queue size is initialised and stored in size
▪ One queue per direction read data write data
▪ tx ISR unloads tx_q from head to tail
▪ rx ISR loads rx_q
▪ Other threads (e.g. main) load tx_q and unload rx_q send_string get_string

▪ Need to wrap pointer at end of buffer to make it circular,


▪ Use “modulus operator” if queue size is not power of two
▪ Use “bitwise and” if queue size is a power of two
tx_isr rx_isr
▪ Queue is empty if tail == head
Serial
▪ Queue is full if (tail + 1) % size == head Interface

31
ASYNCHRONOUS SERIAL (UART)
COMMUNICATIONS

32
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

33
Receiver Basics
Data
bits

Data Sampling

Zero
Time

Tbit*10.5
Tbit*1.5
Time at

Tbit*2.5

Tbit*3.5

Tbit*4.5

Tbit*5.5

Tbit*6.5

Tbit*7.5

Tbit*8.5

Tbit*9.5
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!
34
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

35
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 32x

36
Baud Rate

▪ Need to divide high frequency clock down to desired baud rate * oversampling factor

▪ Example
▪ 24 MHz -> 4800 baud with 16x oversampling
▪ Division factor = 24E6/(4800*16) = 312.5. Must round to closest integer value ( 312 or 313), will
have a slight frequency error.

37
Software for Polled Serial Comm.

void test_polled() {
uart_init(9600);
uart_enable();

while(1) {
uart_tx(uart_rx()); // echos the received character back
}
}

38
SPI COMMUNICATIONS

39
SPI Communication
▪ All chips share bus signals
▪ Clock SCK
▪ Data lines MOSI (master out, slave in) and MISO
(master in, slave out)
▪ Each peripheral has its own chip select line (CS)
▪ Master (MCU) asserts the CS line of only the
peripheral it’s communicating with

▪ 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

40
SPI Example: Secure Digital Card Access
CMD / CLK /
GND VDD
▪ SD cards have two communication modes DAT3 / DI SCLK GND DAT0/
▪ Native 4-bit DAT2 / CS DO
▪ Legacy SPI 1-bit X DAT1/
X
▪ VDD from 2.7 to 3.6 V
▪ CS: Chip Select (active low)

▪ Host sends a six-byte command packet to card


▪ Index, argument, CRC

▪ Host reads bytes from card until card signals it is ready


▪ Card returns
◦ 0xff while busy
◦ 0x00 when ready without errors
◦ 0x01-0x7f when error has occurred

41
I2C COMMUNICATIONS

42
I2C Communication Architecture

Author: Colin M.L. Burnett, Source: Wikimedia

▪ “Inter-Integrated Circuit” bus


▪ Multiple devices connected by a shared serial bus
▪ Bus is typically controlled by master device, slaves respond when addressed
▪ I2C bus has two signal lines
▪ SCL: Serial clock
▪ SDA: Serial data
▪ Full details available in “The I2C-bus Specification”

43
I2C Addressing

▪ Each device (IC) has seven-bit address


▪ Different types of device have different default addresses
▪ Sometimes can select a secondary default address by tying a device pin to a different logic level

▪ What if we treat the first byte of data as a register address?


▪ Can specify registers within a given device: eight bits

44
SERIAL COMMUNICATION PROTOCOLS
COMPARISON

45
Factors to Consider
▪ How fast can the data get through?
▪ Depends on raw bit rate, protocol overhead in packet

▪ How many hardware signals do we need?


▪ May need clock line, chip select lines, etc.

▪ How do we connect multiple devices (topology)?


▪ Dedicated link and hardware per device - point-to-point
▪ One bus for master transmit/slave receive, one bus for slave transmit/master receive
▪ All transmitters and receivers connected to same bus – multi-point

▪ How do we address a target device?


▪ Discrete hardware signal (chip select line)
▪ Address embedded in packet, decoded internally by receiver

▪ How do these factors change as we add more devices?


46
Protocol Trade-Offs
Protocol Speed Signals Req. for Device Topology
Bidirectional Addressing
Communication with
N devices

UART Fast – Tens of Mbit/s 2*N (TxD, RxD) None Point-to-point full
(Point to Point) duplex

UART Fast – Tens of Mbit/s 2 (TxD, RxD) Added by user in Multi-drop


(Multi-drop) software

SPI Fast – Tens of Mbit/s 3+N for SCLK, MOSI, Hardware chip Multi-point full-
MISO, and one SS per select signal per duplex, multi-drop
device device half-duplex buses

I2C Moderate – 100 kbit/s, 400 kbit/s, 1 2 (SCL, SDA) In packet Multi-point half-
Mbit/s, 3.4 Mbit/s. Packet overhead. duplex bus

47

You might also like