SlideShare a Scribd company logo
Embedded System
ENG. KEROLES SHENOUDA
1
Index 1 2
 How to get started with Eclipse
and AVR
 Interfacing an 16×2 character
LCD (Liquid Crystal Display)
 LCD Functionality
 16×2 lcd commands
 LAB: write LCD Driver [8bit] Data
mode
Index 2 3
 Embedded communication
 Main Concepts: Simplex, Half-duplex,
Full-duplex
 Serial Vs Parallel
 Synchronous Communication
 Asynchronous Communication
 Single ended vs differential
 TX/RX relation
Index 3 4
 SPI (Serial Peripheral
Interface)
 Advantages of SPI
 Disadvantages of SPI
 SPI BUS Protocol
 SPI Interface
 How SPI works ?
 Steps for writing data
to an SPI device
 Clock Polarity and
Phase in SPI device
Index 4 5
 Examples
 Simple SPI Write Transaction
 Simple SPI Read Transaction
 SPI Bus 3-Wire and Multi-IO
Configurations
 SPI Bus 3-Wire and Multi-IO
Configurations
 QUAD SPI [QSPI]
 Example: Quad mode fast read
sequence for Spansion S25FL016K or
equivalent
Index 5 6
 SPI ON atmega32
 SPI Block Diagram
 SPI Registers
 SPCR – SPI Control Register
 SPSR – SPI Status Register
 SPSR – SPI Status Register
 SPDR – SPI Data Register is a
read/write register
 SS pin in AVR
Index 6 7
 Code Sequence
 Code Sequence on Master Mode
 Initialize SPI Master Device (with SPI
interrupt)
 Code Sequence on Slave Mode
 Lab 1
 MAX7221 Interfacing and Prog…
 MAX7221 data packet format
 MAX7221 Interfacing and Prog…
 SPI Application
 SPI Vs I2C
Index 7 8
 UART
 THE UART INTERFACE
 UART “Asynchronous ”
frame
 UART on Atmega32
 USART Block Diagram
 Equations for Calculating
Baud Rate Register Setting
 Examples of Baud Rate
Setting
Index 8 9
 Registers
 UART LAB
 UART Driver
 MAX232 IC to convert UART to
RS232
 FT232 (UART to USB)
 References
How to get started with Eclipse and AVR 10
http://www.instructables.com/id/How-to-get-started-with-
Eclipse-and-AVR/
Avr-gcc.exe application error in Eclipse using
Windows 8/10
 http://www.ignitemindz.com/index.php/documents-about-technologies-
2/eclipse-not-working-no-java-virtual-machine-was-found/avr-gcc-exe-
application-error-in-eclipse-using-windows-8
11
Interfacing an 16×2 character LCD
(Liquid Crystal Display)
 LCD stands for liquid crystal display. Now
earlier we used to use 7 segment displays for
display purposes, but now LCD’s are preferred.
The main reason is we need less number of
data bus lines for interfacing LCD’s as
compared to 7 segment displays.
 Other reason is we can print various characters
on the screen.
 Now the basic characters are already saved
inside CGROM(Character Generator ROM).
So you need to send only the ASCII values in
order to display the character on screen
 16×2 LCD means It has 2 rows and 16 columns
12
LCD interfacing 13
LCD interfacing
 a VDD pin for 5 volts
 a VSS pin for ground.
 V0 pin for the adjustment of the LCD contrast.
 Some LCDs even have an LED backlight and are generally the last two
pins.
 the LCD has a row of 8 pins to serve as its port. D0, D1, D2, D3, D4, D5, D6
and D7. These pins are generally used to pass information into the LCD,
but it can also be set to pass information back to the microcontroller
 read/write is microcontroller centric: the LCD "read" mode is the process
of passing information from the LCD to the microcontroller
(microcontroller port set as input or reading or listening).; the LCD
"write" mode is passing information from the microcontroller to the LCD
(microcontroller set to output or writing).
 The pin on the LCD that is responsible for whether the infomation sent is
a character or a control, is the RS pin (Register Select)
 the pin that helps the LCD accept informatin is called the EN pin (Enable)
14
Block Digram 15
 There are three memories in LCD
to manipulate display characters:
 CGROM – character generating
ROM which is responsible for
stored standard character patter
n.
 CGRAM – character generating
RAM which holds custom
character pattern space ( total 8
in 2×16 module).
 DDRAM – data display RAM
which stores ASCII codes.
LCD Functionality 16
(1) to make sure the LCD
is not busy
(2) Control the LCD's
cursor, or display
function
(3) Write a character to
the LCD for it to display
LCD Functionality 17
(1) to make sure the LCD is not busy
a. set the port to receive data on the
microcontroller (Data direction as input).
b. put the LCD in read mode (RW on).
c. put the LCD in command mode (RS off).
And the port now magically contains the data
from the LCD (D7 pin will be ON if the LCD is
busy and OFF if the LCD is not busy).
(2) Control the LCD's
cursor, or display
function
(3) Write a character to
the LCD for it to display
LCD Functionality 18
(1) to make sure the LCD
is not busy(2) Control the LCD's cursor, or display function
(Send a command to the LCD)
• set the port direction as output so you can send
information to the LCD.
• turn RW off so you can write.
• turn RS off for command mode.
• Write the command on D0…D7
• turn on the enable and then turn it off.(delay ~500ns)
The LCD will magically perform the command.
(3) Write a character to
the LCD for it to display
LCD Functionality 19
(1) to make sure the LCD
is not busy
(2) Control the LCD's
cursor, or display
function
• (3) Write a character to the LCD for it to display
Send a character to the LCD: This is the same as sending
a command except the RS is on and the port will equal
the character corresponding to the ASCII code.
• set the port direction as output so you can send
information to the LCD.
• turn RW off so you can write.
• turn RS ON for Data mode.
• Write the command on D0…D7
• turn on the enable and then turn it off.(delay ~500ns)
16×2 lcd commands
COMMAND FUNCTION
20
80 Force cursor to
beginning of the first
line
C0 Force cursor to
beginning of second line
38 Use two lines and 5x7
matrix
83 Cursor line 1 position 3
3C Activate second line
0C3 Jump to second line
position 3
0C1 Jump to second line
position1
16×2 lcd commands 21
Instruction Hex
Function Set: 8-bit, 1 Line, 5x7 Dots 0x30
Function Set: 8-bit, 2 Line, 5x7 Dots 0x38
Function Set: 4-bit, 1 Line, 5x7 Dots 0x20
Function Set: 4-bit, 2 Line, 5x7 Dots 0x28
Entry Mode 0x06
Display off Cursor off
(clearing display without clearing DDRAM content)
0x08
Display on Cursor on 0x0E
Display on Cursor off 0x0C
Display on Cursor blinking 0x0F
Shift entire display left 0x18
Shift entire display right 0x1C
Move cursor left by one character 0x10
Move cursor right by one character 0x14
Clear Display (also clear DDRAM content) 0x01
LAB: write LCD Driver [8bit] Data mode 22
Test your driver by print your name and an
integer number then double number
Solution:LCD 23
24
25
26
27
Embedded communication
28
Physical layer Networks
Infrared (IR)
Radio frequency (RF)
Serial
Protocol
I2CUSB
FireWire
Serial
communication
SPIUART
Time Triggered
Protocol (TTP)
Local Interconnect
Network (LIN)
Media Oriented
System Transport
(MOST)
Controller Area
Network (CAN)
Automotive
protocols
TCP/IP (Ethernet
Module)
Wireless
protocols
Bluetooth
Infrared Data
Association (IrDA)
IEEE 802.11
Main Concepts: Simplex, Half-duplex,
Full-duplex
29
Serial Vs Parallel 30
Synchronous Communication 31
Asynchronous Communication 32
Single ended vs differential 33
TX/RX relation 34
SPI (Serial Peripheral Interface)
 synchronous data transfer
 Full-duplex
 Single Master / multi slave
 Serial interface
 Multiple slave devices are supported through selection with individualslave
select (SS) lines
 The SPI bus was originally started by Motorola Corp. (now Freescale), but in recent years has
become a widely used standard adapted by many semiconductor chip companies
 It can be used to communicate with a serial peripheral device like
external EEPROM or with another microcontroller with an SPI
interface
35
Advantages of SPI
 Higher throughput (Faster)
SPI: 10Mbs – 20Mbs
 Simple Receiver Hardware >>> Simple Shift Register
 Support Multiple Slaves
 Lower power Requirements than I2C.
36
Disadvantages of SPI
 Requires more Pins
 Master must control all communications (Slave doesn’t issue the transaction).
 Separate SS Lines.
 No Flow Control (must know slave speed)
37
SPI BUS Protocol
 These 4 pins, SDI,
SDO, SCLK, and CE,
make the SPI a 4-
wire interface.
 The SDI, SDO,
SCLK, and CE
signals are
alternatively
named as MOSI,
MISO, SCK, and SS.
38
SPI Interface
39
The SPI bus specifies four logic signals:
• SCLK(SCK,CLK) : Serial Clock (output from
master).
• MOSI(SIMO,SDI,DI) : Master Output, Slave
Input (output from master).
• MISO(SIMO,SDO,DO) : Master Input, Slave
Output (output from slave).
• SS (CS,CE,CEN): Slave Select (active low,
output from master).
How SPI works ?
 SPI consists of two shift
registers, one in the master
and the other in the slave
side. Also, there is a clock
generator in the master side
that generates the clock for
the shift registers.
40
HOW SPI WORKS?
The serial-out pin of the master shift register is connected
to the serial-in pin of the slave shift register by MOSI
(Master Out Slave In).
The serial-in pin of the master shift register is connected
to the serial-out pin of the slave shift register by
MISO (Master In Slave Out).
The master clock generator provides clock to the shift
registers in both the master and slave.
The clock input of the shift registers can be falling- or
rising-edge triggered.
Shift registers are 8 bits long. So after 8 clock pulses,
the contents of the two shift registers are
interchanged.
When the master wants to send a byte of data, it places the
byte in its shift register and generates 8 clock pulses.
41
HOW SPI WORKS?
 After 8 clock pulses the byte is transmitted to
the other shift register.
 When the master wants to receive a byte of data,
the slave side should place the byte in its
shift register, and after 8 clock pulses the
data will be received by the master shift
register.
 It must be noted that SPI is full duplex,
meaning that it sends and receives data at the
same time.
42
SPI ” Serial Peripheral Interface ”
How SPI works ?
43
Master Slave
Steps for writing data to an SPI device
 In accessing SPI devices, we
have two modes of operation:
single-byte and multibyte.
Single-byte write:
1. Make CE = 0 to begin writing.
2. The 8-bit address is shifted in,
one bit at a time, with each
edge of SCLK. Notice that A7 = 1
for the write operation, and the
A7 bit goes in first.
44
Steps for writing data to an SPI device
3. After all 8 bits of the address are sent in, the
SPI device expects to receive the data belonging
to that address location immediately.
4. The 8-bit data is shifted in one bit at a time,
with each edge of the SCLK.
5. Make CE = 1 to indicate the end of the write
cycle
45
Steps for writing data to an SPI device
Multi-byte burst write:
 In burst mode, we provide the address of the first location,
followed by the data for that location. From then on, while CE
= 0, consecutive bytes are written to consecutive memory
locations.
 In this mode, the SPI device internally increments the address
location as long as CE is LOW.
 The following steps are used to send (write) multiple bytes of
data in burst mode for SPI devices as shown in Figure 17-5:
1. Make CE = 0 to begin writing.
2. The 8-bit address of the first location is provided and
shifted in, one bit at a time, with each edge of SCLK. Notice
that A7 = 1 for the write operation and the A7 bit goes in
first.
46
Steps for writing data to an SPI device
3. The 8-bit data for the first location is
provided and shifted in, one bit at a time, with
each edge of the SCLK.
4. From then on, we simply provide con secutive
bytes of data to be placed in consecutive memory
locations. In the process, CE must stay low to
indicate that this is a burst mode multibyte
write operation.
5. Make CE = 1 to end writing.
47
Steps for reading data from an SPI device
Single-byte read
1. Make CE = 0 to begin reading.
2. The 8-bit address is shifted in one bit at a time, with each edge of SCLK. Notice that A7
= 0 for the read operation, and the A7 bit goes in first.
3. After all 8 bits of the address are sent in, the SPI device sends out data belonging to
that location.
4. The 8-bit data is shifted out one bit at a time, with each edge of the SCLK.
5. Make CE = 1 to indicate the end of the read cycle
48
Steps for reading data from an SPI device
4. The 8-bit data is shifted out one bit at a time, with each
edge of the SCLK.
5. Make CE = 1 to indicate the end of the read cycle.
Multi-byte burst read
 In burst mode, we provide the address of the first
location only. From then on, while CE = 0, consecutive
bytes are brought out from consecutive memory locations.
 In this mode, the SPI device internally increments the
address location as long as CE is LOW.
 The following steps are used to get (read) multiple bytes
of data in burst mode for SPI devices
49
Steps for reading data from an SPI device
1. Make CE = 0 to begin reading.
2. The 8-bit address of the first location is provided and shifted in, one bit at a time, with
each edge of SCLK. Notice that A7 = 0 for the read operation, and the A7 bit goes in first.
3. The 8-bit data for the first location is shifted out, one bit at a time, with each edge of
the SCLK. From then on, we simply keep getting consecutive bytes of data belonging to
consecutive memory locations. In the process, CE must stay LOW to indicate that this is a
burst mode multibyte read operation.
4. Make CE = 1 to end reading.
50
Steps for reading data from an SPI device
consecutive bytes of data belonging to consecutive memory
locations. In the process, CE must stay LOW to indicate that
this is a burst mode multibyte read operation.
4. Make CE = 1 to end reading.
51
Clock Polarity and Phase in SPI device
 In SPI communication, the master and slave(s) must agree
on the clock polarity and phase with respect to the data.
 Freescale names these two options as CPOL (clock
polarity) and CPHA (clock phase), respectively, and most
companies like Atmel have adopted that convention.
 At CPOL = 0 the base value of the clock is zero, while at
CPOL = 1 the base value of the clock is one. CPHA = 0
means sample on the leading (first) clock edge, while
CPHA = 1 means sample on the trailing (second) clock.
 If the base value of the clock is zero, the leading
(first) clock edge, is the rising edge but if the base
value of the clock is one, the leading (first) clock edge
is falling edge.
52
The base value of clock is Zero
The base value of clock is One
Sample on First Clock Edge
Sample on Second Clock Edge
53
SPI Modes
Clock polarity (CPOL) and clock phase (CPHA)
54
Examples
55
Simple SPI Write Transaction
 Most SPI flash memories have a write status register command that writes one or two bytes of data.
 To write to the status register, the SPI host first enables the slave select line for the current device. The master
then outputs the appropriate instruction followed by two data bytes that define the intended status register
contents. Since the transaction does not need to return any data, the slave device keeps the MISO line in a high
impedance state and the master masks any incoming data. Finally, slave select is de-asserted to complete the
transaction.
56
Simple SPI Read Transaction
 A status register read transaction would be similar to the write transaction, but now takes advantage of
data returned from the slave. After sending the read status register instruction, the slave begins
transmitting data on the MISO line at a rate of one byte per eight clock cycles. The host receives the
bitstream and completes the transaction by de-asserting SS#
57
SPI Bus 3-Wire and Multi-IO
Configurations
 There is also a widely used standard called a 3-wire
interface bus. In a 3-wire interface bus, we have
SCLK and CE, and only a single pin for data
transfer.
 The SPI 4-wire bus can become a 3-wire interface
when the SDI and SDO data pins are tied together.
 But there are some major differences between the SPI
and 3-wire devices in the data transfer protocol.
 For that reason, a device must support the 3-wire
protocol internally in order to be used as a 3-wire
device.
 Many devices such as the DS1306 RTC (real-time
clock) support both SPI and 3-wire protocols.
58
SPI Bus 3-Wire and Multi-IO
Configurations
 In 3-wire mode, MOSI and MISO
lines are combined to a single
bidirectional data
 Transactions are half-duplex to
allow for bidirectional
communication. Reducing the
number of data lines and operating
in half-duplex mode also decreases
maximum possible throughput
59
QUAD SPI [QSPI]
 Multi I/O variants such as dual I/O and
quad I/O add additional data lines to
the standard for increased
throughput. Components that utilize
multi I/O modes can rival the read
speed of parallel devices while still
offering reduced pin counts. This
performance increase enables
random access and direct program
execution from flash memory
(execute-in-place)
60
Example: Quad mode fast read sequence
for Spansion S25FL016K or equivalent
61
Quad IO is gaining
popularity with flash
memories for its increased
performance. Instead of
using a single output and
single input interface, Quad
IO utilizes 4 separate half-
duplex data lines for both
transmitting and receiving
data for up to four times the
performance of standard 4-
wire SPI.
Example: Quad mode fast read sequence
for Spansion S25FL016K or equivalent
62
This example read command for a
Spansion S25FL016K serial NOR
flash device. To read from the
device, a fast read command
(EBh) is first sent by the master on
the first IO line while all others are
tristated. Next, the host sends the
address; since the interface now
has 4 bidirectional data lines, it
can utilize these to send a
complete 24-bit address along
with 8 mode bits in just 8 clock
cycles. The address is then
followed with 2 dummy bytes (4
clock cycles) to allow the device
additional time to set up the initial
address.
SPI ON atmega32
63
SPI Block Diagram 64
SPI on Atmega32
 Register Descriptions
 The AVR contains the following three registers that deal with
SPI:
 SPCR – SPI Control Register – This register is basically the
master register i.e. it contains the bits to initialize SPI and
control it.
 SPSR – SPI Status Register – This is the status register. This
register is used to read the status of the bus lines.
 SPDR – SPI Data Register – The SPI Data Register is the
read/write register where the actual data transfer takes place.
65
SPCR – SPI Control Register
66
Bit 7 – SPIE: SPI Interrupt Enable
This bit causes the SPI interrupt to be executed if SPIF bit in the SPSR Register is set and if the Global
Interrupt Enable bit in SREG is set.
Bit 6 – SPE: SPI Enable
When the SPE bit is written to one, the SPI is enabled. This bit must be set to enable any SPI operations.
Bit 5 – DORD: Data Order
When the DORD bit is written to one, the LSB of the data word is transmitted first.
When the DORD bit is written to zero, the MSB of the data word is transmitted first.
Bit 4 – MSTR: Master/Slave Select
This bit selects Master SPI mode when written to one, and Slave SPI mode when written logic zero. If SS
is configured as an input and is driven low while MSTR is set, MSTR will be cleared, and SPIF in SPSR
will become set. The user will then have to set MSTR to re-enable SPI Master mode.
SPCR – SPI Control Register
 Bit 3 – CPOL: Clock Polarity
 Bit 2 – CPHA: Clock Phase
67
SPCR – SPI Control Register
 Bits 1:0 – SPRn: SPI Clock Rate Select [n = 1:0]
68
SPSR – SPI Status Register 69
Bit 7 – SPIF: SPI Interrupt Flag
1. When a serial transfer is complete, the SPIF Flag is set. An interrupt is
generated if SPIE in SPCR is set
and global interrupts are enabled.
2. If SS is an input and is driven low when the SPI is in Master mode, this
will also set the SPIF Flag. SPIF is cleared by hardware when executing the
corresponding interrupt handling vector.
Alternatively, the SPIF bit is cleared by first reading the SPI Status Register with
SPIF set, then accessing the SPI Data Register (SPDR)
SPSR – SPI Status Register 70
Bit 6 – WCOL: Write Collision Flag
The WCOL bit is set if the SPI Data Register (SPDR) is written during a data
transfer.
The WCOL bit (and the SPIF bit) are cleared by first reading the SPI Status
Register with WCOL set, and then accessing the
SPI Data Register.
SPSR – SPI Status Register 71
Bit 0 – SPI2X: Double SPI Speed Bit
SPDR – SPI Data Register is a read/write
register
 The SPI Data Register is a read/write register used for data transfer between
the Register File and the
SPI Shift Register. Writing to the register initiates data transmission. Reading
the register causes the Shift
Register Receive buffer to be read.
• SPID7 is MSB
• SPID0 is LSB
72
SS pin in AVR
 The Slave Select (SS) pin of the SPI bus is used to
initiate and terminate the data transfer.
 When you are in master mode, you can choose to make
this pin either input or output.
If you make it output, you can make it one or zero by
software.
 When you make the SS pin an input, In this case you
should externally make SS pin high to ensure master SPI
operation.
 If an external device makes the SS pin low, the SPI
module stops working in master mode and
switches to slave mode by clearing the MSTR bit in SPCR,
and then sets the SPIF bit in SPSR
73
SS pin in AVR
 It is highly recommended to make the SS pin output if
you do not want to be interrupted when you are working
in master mode.
 When you are in slave mode, the SS pin is always input
and you cannot control it by software. You should hold
it externally low to activate the SPI. When SS is
driven high, SPI is disabled
74
Code Sequence
 Before you start data transmission, you should set
SPI Mode (Clock Polarity and Clock Phase) by setting
the values of the CPOL and CPHA bits in SPCR.
 You can operate in either master or slave modes.
Master operating mode
 If you want to work in master mode, you should set
the MSTR bit to one. Also you should set SCK
frequency by setting the values of SPI2X, SPR1, and
SPR2.
 Then you should enable SPI by setting the SPIE bit to
one before you start data transmission.
 Writing a byte to the SPI Data Register (SPDR) starts
data exchange by starting the SPI clock generator.
 After shifting the last (8th) bit, the SPI clock
generator stops and the SPIF flag changes to one.
75
Code Sequence
 The byte in the master shift register and the byte in
the slave shift register are exchanged after the last
clock.
 Notice that you cannot write to the SPI Data Register
before transmission is completed, otherwise the
collision happens.
 To get the received data you should read it from SPDR
before the next byte arrives.
 We can use interrupts or poll the SPIF to know when a
byte is exchanged.
76
Code Sequence on Master Mode 77
# define F_CPU 1000000UL // define crystal frequency for delay.h
#include <avr/io.h> // standard AVR header
#include <util/delay.h>
#define SS 4 // Slave Select is Bit No.4
#define MOSI 5 // Master Out Slave In is Bit No.5
#define MISO 6 // Master In Slave Out is Bit No.6
#define SCK 7 // Shift Clock is Bit No.7
void SPI_MasterInit(void){
// Set MOSI, SCK and SS as Output Pins
DDRB |= (1<<MOSI) | (1<<SCK) | (1<<SS) ;
DDRB &= ~(1<<MISO); // Set MISO as an Input Pin
// Enable SPI, Master mode, Shift Clock = CLK /16
SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR0);
}
Code Sequence on Master Mode 78
unsigned char SPI_MasterTransmit(unsigned char cData){
SPDR = cData; // Start transmission
while(!(SPSR & (1<<SPIF))); // Wait for transmission complete
return SPDR; // return the received data
}
Initialize SPI Master Device (with SPI
interrupt)
// Initialize SPI Master Device (with SPI interrupt)
void spi_init_master (void)
{
// Set MOSI, SCK as Output
DDRB=(1<<5)|(1<<3);
// Enable SPI, Set as Master
// Prescaler: Fosc/16, Enable Interrupts
//The MOSI, SCK pins are as per ATMega8
SPCR=(1<<SPE)|(1<<MSTR)|(1<<SPR0)|(1<<SPIE);
// Enable Global Interrupts
sei();
}
79
Code Sequence on Slave Mode 80
Slave Operating Mode
 When AVR is configured as a slave, the function of
the SPI interface depends on the SS pin. If the SS is
driven high, MISO is tri-stated and the SPI interface
sleeps. Only the contents of SPDR may be updated in
this state.
 When SS is driven low, the data will be shifted by
incoming clock pulses on the SCK pin.
 SPIF changes to one when the last bit of a byte has
been shifted completely. Notice that the slave can
place new data to be sent into SPDR before reading
the incoming data; this is because in AVR there are
two one-byte buffers to store received data
Code Sequence on Slave Mode
 In slave mode there is no need to set SCK frequency
because the SCK is generated by the master.
 But you must select the SPI mode (Clock Phase and
Clock Polarity) and Data Order to match with SPI mode
and Data Order of the other side (master device).
 Finally you should enable the SPI by setting the SPIE
bit of SPCR to one.
81
Code Sequence on Slave Mode
#define F_CPU 1000000UL // define crystal frequency for delay.h
#include <avr/io.h> // standard AVR header
#include <util/delay.h>
#define SS 4 // Slave Select is Bit No.4
#define MOSI 5 // Master Out Slave In is Bit No.5
#define MISO 6 // Master In Slave Out is Bit No.6
#define SCK 7 // Shift Clock is Bit No.7
void SPI_SlaveInit(void){
DDRB |= (1<<MISO); // Set MISO as an Output Pin
// Set MOSI, SCK and SS as Input Pins
DDRB &= ~(1<<MOSI) & ~(1<<SCK) & ~(1<<SS) ;
// Enable SPI as a Slave Device
SPCR = (1<<SPE);
}
82
Code Sequence on Slave Mode
unsigned char SPI_SlaveReceive(unsigned char cData){
SPDR = cData; // send cData to master
// Wait for reception complete
while(!(SPSR & (1<<SPIF)));
// Return received data
return SPDR;
}
83
Lab 1
First Clock Edge LSB goes at end
84
MAX7221 Interfacing and Prog…
7-Segment Display:
 In many applications, when you want to
display numbers, 7-segments are the
best choice. These displays are made
of 7 LEDs to show different numbers
plus another LED to display the
decimal point.
85
MAX7221 Interfacing and Prog…
 If you want to connect four 7-segment LEDs directly to a
microcontroller you need 4 x 8 = 32 pins. This is not
feasible.
 The MAX7221 IC is supports up to eight 7-segment LEDs. We
can connect the MAX7221 to the AVR chip using SPI protocol
and control up to eight 7-segment LEDs.
 The MAX7221 contains an internal decoder that can be used to
convert binary numbers to 7-segment codes. That means we do
not need to refresh the 7-segment LEDs.
 All you need to do is to send a binary number to the
MAX7221, and the chip decodes the binary data and displays
the number.
 The device includes analog and digital brightness control,
an 8x8 static RAM that stores each digit, and a test mode
that forces all LEDs on.
86
MAX7221 Pins and Connections
 The MAX7221 is a 24-pin DIP
chip. It can be directly
connected to the AVR and con-
trol up to eight 7-segment
LEDs. A resistor or a
potentiometer is the only
external component that you
need. Next, we will discuss
the pins of the MAX7221.
GND: Pin 4 and pin 9 are the ground. These should
be connected to system ground
Vcc: Pin 19 is the VCC and should be connected to
the +5V.this pin is also the power to drive
the 7-segments and the connecting wire to this
pin should be able to handle 100-300 mA.
87
MAX7221 Pins and Connections
ISET: Pin 18 is ISET and sets the
maximum segment current. This
pin should be connected to VCC
through a resistor. A 10KΩ
resistor can be connected to
this pin. If you want to
manually control the intensity
of the segments' light, you
can replace the resistor with
a 50KΩ potentiometer.
CS :Pin 12 is the chip select pin and should be
connected to the SS pin of the AVR. Serial
data is loaded into the chip while CS is low,
and the last 16 bits of the serial data are
latched on CS's rising edge.
88
MAX7221 Pins and Connections
DIN: Pin 1 is the serial data
input and should be connected
to the MOSI pin of the AVR. On
CLK's rising edge, data on
this pin is loaded into the
internal shift register.
Notice that the MAX7221 uses
the SPI Mode 0, that is, read
on rising edge and change on
falling edge..
CLK: Pin 13 is the serial clock input and should be
connected to the SCK pin of the AVR. On MAX7221 the
clock input is inactive when CS is high.
DOUT: Pin 24 is the serial data output and is used to
connect more than one MAX7221 to a single SPI bus.
89
MAX7221 Pins and Connections
DIG0-DIG7:
The DIG pins are the 7-segment
selector pins and should be
connected to the 7-segments' common
cathode pin. The MAX7221 chip can
control up to eight 7-segment LEDs.
These eight 7-segment dispalys are
designated as DIGO to DIG7.
SEGA…SEGG and DP: These pins select each segment
and should be connected to segments of each 7-
segment accordingly.
90
MAX7221 data packet format
 In MAX7221, data packets are 16 bits long (two bytes). You
should first make CS low before transmitting; then you
transmit two bytes of data and terminate the transmission
by making CS high.
 The first byte (MSBs) of each packet contains the command
control bits, and the second byte is the data to be
displayed.
 The upper four bits (D15-D12) of the command byte are
don't care and the lower four bits (D11-D8) are used to
identify the meaning of the data byte to be followed.
 The second byte (D7-D0) of the two-byte packet is called
the data byte and is the actual data to be displayed or
control the 7-segment driver.
 Table 17-3 shows the binary and hex values of each
command.
91
MAX7221 data packet format 92
MAX7221 data packet format 93
94
95
MAX7221 Interfacing and Prog…
#include <avr/io.h> //standard AVR header
#define SS 4
#define MOSI 5
#define SCK 7
void execute (unsigned char cmd, unsigned char data){
// initializing the packet by pulling SS low
PORTB &= ~(1<<SS) ;
SPDR = cmd; // start CMD transmission
// wait cmd transfer to finish
while (!(SPSR & (1<<SPIF) ) );
// start DATA transmission
SPDR = data;
// wait data transfer to finish
while (!(SPSR & (1<<SPIF) ) ) ;
96
MAX7221 Interfacing and Prog…
// terminate the packet by pulling SS high
PORTB |= 1<<SS;}
int main (void){
// MOSI, SCK and SS are output
DDRB = (1<<MOSI) | (1<<SCK) | (1<<SS) ;
// enable SPI as master, SCk = FOsc/16
SPCR = (1<<SPE) | (1<<MSTR)| (1<<SPR0);
execute(0x09,0x03); // decode only digit 0 and 1
execute(0x0B,0x02); // Set ScanLimit(upto digit 2)
execute(0x0A,0x0F); // max intensity
execute(0x0C,0x01); // Turn On Display
execute(0x01,0x07); // digit 0 is 7
execute(0x02,0x05); // digit 1 is 5
execute(0x03,0b00010111); // digit 2 is h
while(1); return 0;
}
97
MAX7221 Interfacing and Prog…
execute(0x09,0x03);
98
SPI Application 99
SPI Vs I2C 100
UART
101
USART - Universal Synchronous and Asynchronous serial Receiver
and Transmitter
 Support Full Duplex mode.(two wires)
 Serial interface
 Used to:
 Make a communication channel between our micro-controller
and our computer
 talk to some sensors/chips, the most used ones are serial
backpacks for lcd’s and graphical lcd’s and GPS modules that
use almost always an serial interface.
 The serial protocol is a fairly old protocol created many years
ago it was used by Teletypes and terminals
102
THE UART INTERFACE
103
Compared to I2C, using the UART is darn-easy. UART stands for Universal Asynchronous
Receive/Transmit. The hardware can also run in synchronous mode, so it is often called a
USART. A good article about the hardware is at avrbeginners.net. And a good programming
reference is Dean Camera’s UART article at fourwalledcubicle.com.
As opposed to SPI and I2C, which are often used for binary data exchange between hardware
devices, UART is often used for transmission of (slower) ASCII data. For example, you might
use the UART for keyboard input or monitor/character LCD output. Speedy SPI transfers data
to dedicated hardware devices at MHz speeds, while UART transfers are a thousand times
slower.
UART “Asynchronous ” frame
104
Each data frame consists of
a start bit, a variable number
of data bits, an optional
parity bit, and 1 or 2 stop
bits. The most common
configuration is 1 start bit, 8
data bits, no parity bit, and 1
stop bit (“8N1”).
In asynchronous mode, there is no clock line:
data is transmitted on the transmit line (Tx) and
received on the receive line (Rx).
The UART is initialized by configuring control registers that
determine the baud rate, parity, number of stop bits:
UART frame 105
UART on Atmega32
 Features
• Full Duplex Operation (Independent Serial Receive and Transmit Registers)
• Asynchronous or Synchronous Operation
• Master or Slave Clocked Synchronous Operation
• High Resolution Baud Rate Generator
• Supports Serial Frames with 5, 6, 7, 8, or 9 data bits and 1 or 2 stop bits
• Odd or Even Parity Generation and Parity Check Supported by Hardware
• Data OverRun Detection
• Framing Error Detection
• Noise Filtering Includes False Start Bit Detection and Digital Low Pass Filter
• Three Separate Interrupts on TX Complete, TX Data Register Empty and RX
Complete
• Multi-processor Communication Mode
• Double Speed Asynchronous Communication Mode
106
USART Block Diagram
107
Equations for Calculating Baud Rate
Register Setting
108
Examples of Baud Rate Setting 109
Registers 110
UDR – USART I/O Data Register 111
UCSRA – USART Control and Status
Register A
112
UCSRB – USART Control and Status
Register B
113
UCSRC – USART Control and Status
Register C
114
UBRRL – USART Baud Rate Register Low 115
UBBRH – USART Baud Rate Register
High
116
UART LAB 117
UART Driver 118
main.c 119
MAX232 IC to convert UART to RS232 120
FT232 (UART to USB) 121
References
 https://www.newbiehack.com/MicrocontrollersABeginnersGuideIntroductiona
ndInterfacinganLCD.aspx
 http://www.slideshare.net/MathivananNatarajan/asynchronous-serial-data-
communication-and-standards
122

More Related Content

PDF
Instruction formats-in-8086
PPTX
Lecture 3 instruction set
DOCX
Arm7 Interfacing examples
PPTX
Rtos concepts
PPT
Programmable Logic Devices Plds
PDF
Computer organization memory
PPT
PPTX
Addressing Modes Of 8086
Instruction formats-in-8086
Lecture 3 instruction set
Arm7 Interfacing examples
Rtos concepts
Programmable Logic Devices Plds
Computer organization memory
Addressing Modes Of 8086

What's hot (20)

PPTX
8086 Interrupts & With DOS and BIOS by vijay
PPTX
AMBA Ahb 2.0
PDF
Unit II Arm 7 Introduction
PPTX
Pin diagram 8085
PPTX
8255 Programmable parallel I/O
PPTX
DMA presentation [By- Digvijay]
PPT
Vino's 8086 interrupts
PDF
Lecture 05 pic io port programming
PPTX
Direct memory access (dma)
PPTX
Interrupts on 8086 microprocessor by vijay kumar.k
PDF
Pcie basic
PPTX
Memory Segmentation of 8086
PDF
communication interfaces-Embedded real time systems
PPTX
Intel x86 and ARM Data types
PPTX
Stack and subroutine
PPTX
Semiconductor memories
PPT
11 instruction sets addressing modes
PDF
Intel x86 Architecture
PPTX
SRAM DRAM
8086 Interrupts & With DOS and BIOS by vijay
AMBA Ahb 2.0
Unit II Arm 7 Introduction
Pin diagram 8085
8255 Programmable parallel I/O
DMA presentation [By- Digvijay]
Vino's 8086 interrupts
Lecture 05 pic io port programming
Direct memory access (dma)
Interrupts on 8086 microprocessor by vijay kumar.k
Pcie basic
Memory Segmentation of 8086
communication interfaces-Embedded real time systems
Intel x86 and ARM Data types
Stack and subroutine
Semiconductor memories
11 instruction sets addressing modes
Intel x86 Architecture
SRAM DRAM
Ad

Viewers also liked (20)

PDF
C programming session3
PDF
C programming part4
PPTX
Embedded C programming session10
PDF
Microcontroller part 1
PDF
Microcontroller part 2
PDF
C programming session7
PDF
C programming part2
PDF
K vector embedded_linux_workshop
PDF
Microcontroller part 3
PDF
C programming session8
PDF
C programming first_session
PDF
Automative basics v3
PDF
Microcontroller part 5
PDF
C programming part2
PDF
C programming session5
PDF
C programming part4
PDF
Microcontroller part 9_v1
PDF
Microcontroller part 4
PDF
Microcontroller part 1
PDF
Microcontroller part 2
C programming session3
C programming part4
Embedded C programming session10
Microcontroller part 1
Microcontroller part 2
C programming session7
C programming part2
K vector embedded_linux_workshop
Microcontroller part 3
C programming session8
C programming first_session
Automative basics v3
Microcontroller part 5
C programming part2
C programming session5
C programming part4
Microcontroller part 9_v1
Microcontroller part 4
Microcontroller part 1
Microcontroller part 2
Ad

Similar to Microcontroller part 4 (20)

PPTX
Basic of Firmware & Embedded Software Programming in C
PDF
Lcd tutorial
PPTX
LCD Interacing with 8051
PPTX
Lcd interfacing with microprocessor 8051
PDF
PPTX
Embedded systems and robotics by scmandota
PPTX
Badal sharma
PDF
Lecture mp 7(interface)
PPT
Lcd interface with atmega32 avr best.ppt
PPTX
Introduction to Embedded System: Chapter 2 (4th portion)
PPTX
UNI T 6- SPI_I2C_Lecture8.pptx
PPTX
UNIT 5.pptx
PPTX
UNIT 5 Interfacing and Mixed Signal Controller.pptx
DOC
Moving message display
PPTX
Micro c lab8(serial communication)
PPTX
LCD_Example.pptx
DOCX
Embedded System[586]
PPTX
131080111003 mci
PPT
how to generate sms
PPT
Lcd interfacing1
Basic of Firmware & Embedded Software Programming in C
Lcd tutorial
LCD Interacing with 8051
Lcd interfacing with microprocessor 8051
Embedded systems and robotics by scmandota
Badal sharma
Lecture mp 7(interface)
Lcd interface with atmega32 avr best.ppt
Introduction to Embedded System: Chapter 2 (4th portion)
UNI T 6- SPI_I2C_Lecture8.pptx
UNIT 5.pptx
UNIT 5 Interfacing and Mixed Signal Controller.pptx
Moving message display
Micro c lab8(serial communication)
LCD_Example.pptx
Embedded System[586]
131080111003 mci
how to generate sms
Lcd interfacing1

More from Keroles karam khalil (20)

PDF
C basics quiz part 1_solution
PDF
Autosar Basics hand book_v1
PDF
Automotive embedded systems part6 v2
PDF
Automotive embedded systems part5 v2
PDF
PDF
Automotive embedded systems part7 v1
PDF
Automotive embedded systems part6 v1
PDF
Automotive embedded systems part5 v1
PDF
Automotive embedded systems part4 v1
PDF
Automotive embedded systems part3 v1
PDF
Automotive embedded systems part2 v1
PDF
Automotive embedded systems part1 v1
PDF
Automotive embedded systems part8 v1
PDF
C programming session10
PDF
C programming session9 -
DOCX
PDF
Homework 5 solution
PDF
C programming session8
C basics quiz part 1_solution
Autosar Basics hand book_v1
Automotive embedded systems part6 v2
Automotive embedded systems part5 v2
Automotive embedded systems part7 v1
Automotive embedded systems part6 v1
Automotive embedded systems part5 v1
Automotive embedded systems part4 v1
Automotive embedded systems part3 v1
Automotive embedded systems part2 v1
Automotive embedded systems part1 v1
Automotive embedded systems part8 v1
C programming session10
C programming session9 -
Homework 5 solution
C programming session8

Recently uploaded (20)

PPTX
UNIT 4 Total Quality Management .pptx
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PPT
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PDF
Well-logging-methods_new................
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
DOCX
573137875-Attendance-Management-System-original
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PPTX
Construction Project Organization Group 2.pptx
PPTX
web development for engineering and engineering
PDF
Digital Logic Computer Design lecture notes
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
UNIT 4 Total Quality Management .pptx
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
CYBER-CRIMES AND SECURITY A guide to understanding
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Well-logging-methods_new................
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
573137875-Attendance-Management-System-original
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
Model Code of Practice - Construction Work - 21102022 .pdf
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
Construction Project Organization Group 2.pptx
web development for engineering and engineering
Digital Logic Computer Design lecture notes
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT

Microcontroller part 4

  • 2. Index 1 2  How to get started with Eclipse and AVR  Interfacing an 16×2 character LCD (Liquid Crystal Display)  LCD Functionality  16×2 lcd commands  LAB: write LCD Driver [8bit] Data mode
  • 3. Index 2 3  Embedded communication  Main Concepts: Simplex, Half-duplex, Full-duplex  Serial Vs Parallel  Synchronous Communication  Asynchronous Communication  Single ended vs differential  TX/RX relation
  • 4. Index 3 4  SPI (Serial Peripheral Interface)  Advantages of SPI  Disadvantages of SPI  SPI BUS Protocol  SPI Interface  How SPI works ?  Steps for writing data to an SPI device  Clock Polarity and Phase in SPI device
  • 5. Index 4 5  Examples  Simple SPI Write Transaction  Simple SPI Read Transaction  SPI Bus 3-Wire and Multi-IO Configurations  SPI Bus 3-Wire and Multi-IO Configurations  QUAD SPI [QSPI]  Example: Quad mode fast read sequence for Spansion S25FL016K or equivalent
  • 6. Index 5 6  SPI ON atmega32  SPI Block Diagram  SPI Registers  SPCR – SPI Control Register  SPSR – SPI Status Register  SPSR – SPI Status Register  SPDR – SPI Data Register is a read/write register  SS pin in AVR
  • 7. Index 6 7  Code Sequence  Code Sequence on Master Mode  Initialize SPI Master Device (with SPI interrupt)  Code Sequence on Slave Mode  Lab 1  MAX7221 Interfacing and Prog…  MAX7221 data packet format  MAX7221 Interfacing and Prog…  SPI Application  SPI Vs I2C
  • 8. Index 7 8  UART  THE UART INTERFACE  UART “Asynchronous ” frame  UART on Atmega32  USART Block Diagram  Equations for Calculating Baud Rate Register Setting  Examples of Baud Rate Setting
  • 9. Index 8 9  Registers  UART LAB  UART Driver  MAX232 IC to convert UART to RS232  FT232 (UART to USB)  References
  • 10. How to get started with Eclipse and AVR 10 http://www.instructables.com/id/How-to-get-started-with- Eclipse-and-AVR/
  • 11. Avr-gcc.exe application error in Eclipse using Windows 8/10  http://www.ignitemindz.com/index.php/documents-about-technologies- 2/eclipse-not-working-no-java-virtual-machine-was-found/avr-gcc-exe- application-error-in-eclipse-using-windows-8 11
  • 12. Interfacing an 16×2 character LCD (Liquid Crystal Display)  LCD stands for liquid crystal display. Now earlier we used to use 7 segment displays for display purposes, but now LCD’s are preferred. The main reason is we need less number of data bus lines for interfacing LCD’s as compared to 7 segment displays.  Other reason is we can print various characters on the screen.  Now the basic characters are already saved inside CGROM(Character Generator ROM). So you need to send only the ASCII values in order to display the character on screen  16×2 LCD means It has 2 rows and 16 columns 12
  • 14. LCD interfacing  a VDD pin for 5 volts  a VSS pin for ground.  V0 pin for the adjustment of the LCD contrast.  Some LCDs even have an LED backlight and are generally the last two pins.  the LCD has a row of 8 pins to serve as its port. D0, D1, D2, D3, D4, D5, D6 and D7. These pins are generally used to pass information into the LCD, but it can also be set to pass information back to the microcontroller  read/write is microcontroller centric: the LCD "read" mode is the process of passing information from the LCD to the microcontroller (microcontroller port set as input or reading or listening).; the LCD "write" mode is passing information from the microcontroller to the LCD (microcontroller set to output or writing).  The pin on the LCD that is responsible for whether the infomation sent is a character or a control, is the RS pin (Register Select)  the pin that helps the LCD accept informatin is called the EN pin (Enable) 14
  • 15. Block Digram 15  There are three memories in LCD to manipulate display characters:  CGROM – character generating ROM which is responsible for stored standard character patter n.  CGRAM – character generating RAM which holds custom character pattern space ( total 8 in 2×16 module).  DDRAM – data display RAM which stores ASCII codes.
  • 16. LCD Functionality 16 (1) to make sure the LCD is not busy (2) Control the LCD's cursor, or display function (3) Write a character to the LCD for it to display
  • 17. LCD Functionality 17 (1) to make sure the LCD is not busy a. set the port to receive data on the microcontroller (Data direction as input). b. put the LCD in read mode (RW on). c. put the LCD in command mode (RS off). And the port now magically contains the data from the LCD (D7 pin will be ON if the LCD is busy and OFF if the LCD is not busy). (2) Control the LCD's cursor, or display function (3) Write a character to the LCD for it to display
  • 18. LCD Functionality 18 (1) to make sure the LCD is not busy(2) Control the LCD's cursor, or display function (Send a command to the LCD) • set the port direction as output so you can send information to the LCD. • turn RW off so you can write. • turn RS off for command mode. • Write the command on D0…D7 • turn on the enable and then turn it off.(delay ~500ns) The LCD will magically perform the command. (3) Write a character to the LCD for it to display
  • 19. LCD Functionality 19 (1) to make sure the LCD is not busy (2) Control the LCD's cursor, or display function • (3) Write a character to the LCD for it to display Send a character to the LCD: This is the same as sending a command except the RS is on and the port will equal the character corresponding to the ASCII code. • set the port direction as output so you can send information to the LCD. • turn RW off so you can write. • turn RS ON for Data mode. • Write the command on D0…D7 • turn on the enable and then turn it off.(delay ~500ns)
  • 20. 16×2 lcd commands COMMAND FUNCTION 20 80 Force cursor to beginning of the first line C0 Force cursor to beginning of second line 38 Use two lines and 5x7 matrix 83 Cursor line 1 position 3 3C Activate second line 0C3 Jump to second line position 3 0C1 Jump to second line position1
  • 21. 16×2 lcd commands 21 Instruction Hex Function Set: 8-bit, 1 Line, 5x7 Dots 0x30 Function Set: 8-bit, 2 Line, 5x7 Dots 0x38 Function Set: 4-bit, 1 Line, 5x7 Dots 0x20 Function Set: 4-bit, 2 Line, 5x7 Dots 0x28 Entry Mode 0x06 Display off Cursor off (clearing display without clearing DDRAM content) 0x08 Display on Cursor on 0x0E Display on Cursor off 0x0C Display on Cursor blinking 0x0F Shift entire display left 0x18 Shift entire display right 0x1C Move cursor left by one character 0x10 Move cursor right by one character 0x14 Clear Display (also clear DDRAM content) 0x01
  • 22. LAB: write LCD Driver [8bit] Data mode 22 Test your driver by print your name and an integer number then double number
  • 24. 24
  • 25. 25
  • 26. 26
  • 27. 27
  • 28. Embedded communication 28 Physical layer Networks Infrared (IR) Radio frequency (RF) Serial Protocol I2CUSB FireWire Serial communication SPIUART Time Triggered Protocol (TTP) Local Interconnect Network (LIN) Media Oriented System Transport (MOST) Controller Area Network (CAN) Automotive protocols TCP/IP (Ethernet Module) Wireless protocols Bluetooth Infrared Data Association (IrDA) IEEE 802.11
  • 29. Main Concepts: Simplex, Half-duplex, Full-duplex 29
  • 33. Single ended vs differential 33
  • 35. SPI (Serial Peripheral Interface)  synchronous data transfer  Full-duplex  Single Master / multi slave  Serial interface  Multiple slave devices are supported through selection with individualslave select (SS) lines  The SPI bus was originally started by Motorola Corp. (now Freescale), but in recent years has become a widely used standard adapted by many semiconductor chip companies  It can be used to communicate with a serial peripheral device like external EEPROM or with another microcontroller with an SPI interface 35
  • 36. Advantages of SPI  Higher throughput (Faster) SPI: 10Mbs – 20Mbs  Simple Receiver Hardware >>> Simple Shift Register  Support Multiple Slaves  Lower power Requirements than I2C. 36
  • 37. Disadvantages of SPI  Requires more Pins  Master must control all communications (Slave doesn’t issue the transaction).  Separate SS Lines.  No Flow Control (must know slave speed) 37
  • 38. SPI BUS Protocol  These 4 pins, SDI, SDO, SCLK, and CE, make the SPI a 4- wire interface.  The SDI, SDO, SCLK, and CE signals are alternatively named as MOSI, MISO, SCK, and SS. 38
  • 39. SPI Interface 39 The SPI bus specifies four logic signals: • SCLK(SCK,CLK) : Serial Clock (output from master). • MOSI(SIMO,SDI,DI) : Master Output, Slave Input (output from master). • MISO(SIMO,SDO,DO) : Master Input, Slave Output (output from slave). • SS (CS,CE,CEN): Slave Select (active low, output from master).
  • 40. How SPI works ?  SPI consists of two shift registers, one in the master and the other in the slave side. Also, there is a clock generator in the master side that generates the clock for the shift registers. 40
  • 41. HOW SPI WORKS? The serial-out pin of the master shift register is connected to the serial-in pin of the slave shift register by MOSI (Master Out Slave In). The serial-in pin of the master shift register is connected to the serial-out pin of the slave shift register by MISO (Master In Slave Out). The master clock generator provides clock to the shift registers in both the master and slave. The clock input of the shift registers can be falling- or rising-edge triggered. Shift registers are 8 bits long. So after 8 clock pulses, the contents of the two shift registers are interchanged. When the master wants to send a byte of data, it places the byte in its shift register and generates 8 clock pulses. 41
  • 42. HOW SPI WORKS?  After 8 clock pulses the byte is transmitted to the other shift register.  When the master wants to receive a byte of data, the slave side should place the byte in its shift register, and after 8 clock pulses the data will be received by the master shift register.  It must be noted that SPI is full duplex, meaning that it sends and receives data at the same time. 42
  • 43. SPI ” Serial Peripheral Interface ” How SPI works ? 43 Master Slave
  • 44. Steps for writing data to an SPI device  In accessing SPI devices, we have two modes of operation: single-byte and multibyte. Single-byte write: 1. Make CE = 0 to begin writing. 2. The 8-bit address is shifted in, one bit at a time, with each edge of SCLK. Notice that A7 = 1 for the write operation, and the A7 bit goes in first. 44
  • 45. Steps for writing data to an SPI device 3. After all 8 bits of the address are sent in, the SPI device expects to receive the data belonging to that address location immediately. 4. The 8-bit data is shifted in one bit at a time, with each edge of the SCLK. 5. Make CE = 1 to indicate the end of the write cycle 45
  • 46. Steps for writing data to an SPI device Multi-byte burst write:  In burst mode, we provide the address of the first location, followed by the data for that location. From then on, while CE = 0, consecutive bytes are written to consecutive memory locations.  In this mode, the SPI device internally increments the address location as long as CE is LOW.  The following steps are used to send (write) multiple bytes of data in burst mode for SPI devices as shown in Figure 17-5: 1. Make CE = 0 to begin writing. 2. The 8-bit address of the first location is provided and shifted in, one bit at a time, with each edge of SCLK. Notice that A7 = 1 for the write operation and the A7 bit goes in first. 46
  • 47. Steps for writing data to an SPI device 3. The 8-bit data for the first location is provided and shifted in, one bit at a time, with each edge of the SCLK. 4. From then on, we simply provide con secutive bytes of data to be placed in consecutive memory locations. In the process, CE must stay low to indicate that this is a burst mode multibyte write operation. 5. Make CE = 1 to end writing. 47
  • 48. Steps for reading data from an SPI device Single-byte read 1. Make CE = 0 to begin reading. 2. The 8-bit address is shifted in one bit at a time, with each edge of SCLK. Notice that A7 = 0 for the read operation, and the A7 bit goes in first. 3. After all 8 bits of the address are sent in, the SPI device sends out data belonging to that location. 4. The 8-bit data is shifted out one bit at a time, with each edge of the SCLK. 5. Make CE = 1 to indicate the end of the read cycle 48
  • 49. Steps for reading data from an SPI device 4. The 8-bit data is shifted out one bit at a time, with each edge of the SCLK. 5. Make CE = 1 to indicate the end of the read cycle. Multi-byte burst read  In burst mode, we provide the address of the first location only. From then on, while CE = 0, consecutive bytes are brought out from consecutive memory locations.  In this mode, the SPI device internally increments the address location as long as CE is LOW.  The following steps are used to get (read) multiple bytes of data in burst mode for SPI devices 49
  • 50. Steps for reading data from an SPI device 1. Make CE = 0 to begin reading. 2. The 8-bit address of the first location is provided and shifted in, one bit at a time, with each edge of SCLK. Notice that A7 = 0 for the read operation, and the A7 bit goes in first. 3. The 8-bit data for the first location is shifted out, one bit at a time, with each edge of the SCLK. From then on, we simply keep getting consecutive bytes of data belonging to consecutive memory locations. In the process, CE must stay LOW to indicate that this is a burst mode multibyte read operation. 4. Make CE = 1 to end reading. 50
  • 51. Steps for reading data from an SPI device consecutive bytes of data belonging to consecutive memory locations. In the process, CE must stay LOW to indicate that this is a burst mode multibyte read operation. 4. Make CE = 1 to end reading. 51
  • 52. Clock Polarity and Phase in SPI device  In SPI communication, the master and slave(s) must agree on the clock polarity and phase with respect to the data.  Freescale names these two options as CPOL (clock polarity) and CPHA (clock phase), respectively, and most companies like Atmel have adopted that convention.  At CPOL = 0 the base value of the clock is zero, while at CPOL = 1 the base value of the clock is one. CPHA = 0 means sample on the leading (first) clock edge, while CPHA = 1 means sample on the trailing (second) clock.  If the base value of the clock is zero, the leading (first) clock edge, is the rising edge but if the base value of the clock is one, the leading (first) clock edge is falling edge. 52
  • 53. The base value of clock is Zero The base value of clock is One Sample on First Clock Edge Sample on Second Clock Edge 53
  • 54. SPI Modes Clock polarity (CPOL) and clock phase (CPHA) 54
  • 56. Simple SPI Write Transaction  Most SPI flash memories have a write status register command that writes one or two bytes of data.  To write to the status register, the SPI host first enables the slave select line for the current device. The master then outputs the appropriate instruction followed by two data bytes that define the intended status register contents. Since the transaction does not need to return any data, the slave device keeps the MISO line in a high impedance state and the master masks any incoming data. Finally, slave select is de-asserted to complete the transaction. 56
  • 57. Simple SPI Read Transaction  A status register read transaction would be similar to the write transaction, but now takes advantage of data returned from the slave. After sending the read status register instruction, the slave begins transmitting data on the MISO line at a rate of one byte per eight clock cycles. The host receives the bitstream and completes the transaction by de-asserting SS# 57
  • 58. SPI Bus 3-Wire and Multi-IO Configurations  There is also a widely used standard called a 3-wire interface bus. In a 3-wire interface bus, we have SCLK and CE, and only a single pin for data transfer.  The SPI 4-wire bus can become a 3-wire interface when the SDI and SDO data pins are tied together.  But there are some major differences between the SPI and 3-wire devices in the data transfer protocol.  For that reason, a device must support the 3-wire protocol internally in order to be used as a 3-wire device.  Many devices such as the DS1306 RTC (real-time clock) support both SPI and 3-wire protocols. 58
  • 59. SPI Bus 3-Wire and Multi-IO Configurations  In 3-wire mode, MOSI and MISO lines are combined to a single bidirectional data  Transactions are half-duplex to allow for bidirectional communication. Reducing the number of data lines and operating in half-duplex mode also decreases maximum possible throughput 59
  • 60. QUAD SPI [QSPI]  Multi I/O variants such as dual I/O and quad I/O add additional data lines to the standard for increased throughput. Components that utilize multi I/O modes can rival the read speed of parallel devices while still offering reduced pin counts. This performance increase enables random access and direct program execution from flash memory (execute-in-place) 60
  • 61. Example: Quad mode fast read sequence for Spansion S25FL016K or equivalent 61 Quad IO is gaining popularity with flash memories for its increased performance. Instead of using a single output and single input interface, Quad IO utilizes 4 separate half- duplex data lines for both transmitting and receiving data for up to four times the performance of standard 4- wire SPI.
  • 62. Example: Quad mode fast read sequence for Spansion S25FL016K or equivalent 62 This example read command for a Spansion S25FL016K serial NOR flash device. To read from the device, a fast read command (EBh) is first sent by the master on the first IO line while all others are tristated. Next, the host sends the address; since the interface now has 4 bidirectional data lines, it can utilize these to send a complete 24-bit address along with 8 mode bits in just 8 clock cycles. The address is then followed with 2 dummy bytes (4 clock cycles) to allow the device additional time to set up the initial address.
  • 65. SPI on Atmega32  Register Descriptions  The AVR contains the following three registers that deal with SPI:  SPCR – SPI Control Register – This register is basically the master register i.e. it contains the bits to initialize SPI and control it.  SPSR – SPI Status Register – This is the status register. This register is used to read the status of the bus lines.  SPDR – SPI Data Register – The SPI Data Register is the read/write register where the actual data transfer takes place. 65
  • 66. SPCR – SPI Control Register 66 Bit 7 – SPIE: SPI Interrupt Enable This bit causes the SPI interrupt to be executed if SPIF bit in the SPSR Register is set and if the Global Interrupt Enable bit in SREG is set. Bit 6 – SPE: SPI Enable When the SPE bit is written to one, the SPI is enabled. This bit must be set to enable any SPI operations. Bit 5 – DORD: Data Order When the DORD bit is written to one, the LSB of the data word is transmitted first. When the DORD bit is written to zero, the MSB of the data word is transmitted first. Bit 4 – MSTR: Master/Slave Select This bit selects Master SPI mode when written to one, and Slave SPI mode when written logic zero. If SS is configured as an input and is driven low while MSTR is set, MSTR will be cleared, and SPIF in SPSR will become set. The user will then have to set MSTR to re-enable SPI Master mode.
  • 67. SPCR – SPI Control Register  Bit 3 – CPOL: Clock Polarity  Bit 2 – CPHA: Clock Phase 67
  • 68. SPCR – SPI Control Register  Bits 1:0 – SPRn: SPI Clock Rate Select [n = 1:0] 68
  • 69. SPSR – SPI Status Register 69 Bit 7 – SPIF: SPI Interrupt Flag 1. When a serial transfer is complete, the SPIF Flag is set. An interrupt is generated if SPIE in SPCR is set and global interrupts are enabled. 2. If SS is an input and is driven low when the SPI is in Master mode, this will also set the SPIF Flag. SPIF is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, the SPIF bit is cleared by first reading the SPI Status Register with SPIF set, then accessing the SPI Data Register (SPDR)
  • 70. SPSR – SPI Status Register 70 Bit 6 – WCOL: Write Collision Flag The WCOL bit is set if the SPI Data Register (SPDR) is written during a data transfer. The WCOL bit (and the SPIF bit) are cleared by first reading the SPI Status Register with WCOL set, and then accessing the SPI Data Register.
  • 71. SPSR – SPI Status Register 71 Bit 0 – SPI2X: Double SPI Speed Bit
  • 72. SPDR – SPI Data Register is a read/write register  The SPI Data Register is a read/write register used for data transfer between the Register File and the SPI Shift Register. Writing to the register initiates data transmission. Reading the register causes the Shift Register Receive buffer to be read. • SPID7 is MSB • SPID0 is LSB 72
  • 73. SS pin in AVR  The Slave Select (SS) pin of the SPI bus is used to initiate and terminate the data transfer.  When you are in master mode, you can choose to make this pin either input or output. If you make it output, you can make it one or zero by software.  When you make the SS pin an input, In this case you should externally make SS pin high to ensure master SPI operation.  If an external device makes the SS pin low, the SPI module stops working in master mode and switches to slave mode by clearing the MSTR bit in SPCR, and then sets the SPIF bit in SPSR 73
  • 74. SS pin in AVR  It is highly recommended to make the SS pin output if you do not want to be interrupted when you are working in master mode.  When you are in slave mode, the SS pin is always input and you cannot control it by software. You should hold it externally low to activate the SPI. When SS is driven high, SPI is disabled 74
  • 75. Code Sequence  Before you start data transmission, you should set SPI Mode (Clock Polarity and Clock Phase) by setting the values of the CPOL and CPHA bits in SPCR.  You can operate in either master or slave modes. Master operating mode  If you want to work in master mode, you should set the MSTR bit to one. Also you should set SCK frequency by setting the values of SPI2X, SPR1, and SPR2.  Then you should enable SPI by setting the SPIE bit to one before you start data transmission.  Writing a byte to the SPI Data Register (SPDR) starts data exchange by starting the SPI clock generator.  After shifting the last (8th) bit, the SPI clock generator stops and the SPIF flag changes to one. 75
  • 76. Code Sequence  The byte in the master shift register and the byte in the slave shift register are exchanged after the last clock.  Notice that you cannot write to the SPI Data Register before transmission is completed, otherwise the collision happens.  To get the received data you should read it from SPDR before the next byte arrives.  We can use interrupts or poll the SPIF to know when a byte is exchanged. 76
  • 77. Code Sequence on Master Mode 77 # define F_CPU 1000000UL // define crystal frequency for delay.h #include <avr/io.h> // standard AVR header #include <util/delay.h> #define SS 4 // Slave Select is Bit No.4 #define MOSI 5 // Master Out Slave In is Bit No.5 #define MISO 6 // Master In Slave Out is Bit No.6 #define SCK 7 // Shift Clock is Bit No.7 void SPI_MasterInit(void){ // Set MOSI, SCK and SS as Output Pins DDRB |= (1<<MOSI) | (1<<SCK) | (1<<SS) ; DDRB &= ~(1<<MISO); // Set MISO as an Input Pin // Enable SPI, Master mode, Shift Clock = CLK /16 SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR0); }
  • 78. Code Sequence on Master Mode 78 unsigned char SPI_MasterTransmit(unsigned char cData){ SPDR = cData; // Start transmission while(!(SPSR & (1<<SPIF))); // Wait for transmission complete return SPDR; // return the received data }
  • 79. Initialize SPI Master Device (with SPI interrupt) // Initialize SPI Master Device (with SPI interrupt) void spi_init_master (void) { // Set MOSI, SCK as Output DDRB=(1<<5)|(1<<3); // Enable SPI, Set as Master // Prescaler: Fosc/16, Enable Interrupts //The MOSI, SCK pins are as per ATMega8 SPCR=(1<<SPE)|(1<<MSTR)|(1<<SPR0)|(1<<SPIE); // Enable Global Interrupts sei(); } 79
  • 80. Code Sequence on Slave Mode 80 Slave Operating Mode  When AVR is configured as a slave, the function of the SPI interface depends on the SS pin. If the SS is driven high, MISO is tri-stated and the SPI interface sleeps. Only the contents of SPDR may be updated in this state.  When SS is driven low, the data will be shifted by incoming clock pulses on the SCK pin.  SPIF changes to one when the last bit of a byte has been shifted completely. Notice that the slave can place new data to be sent into SPDR before reading the incoming data; this is because in AVR there are two one-byte buffers to store received data
  • 81. Code Sequence on Slave Mode  In slave mode there is no need to set SCK frequency because the SCK is generated by the master.  But you must select the SPI mode (Clock Phase and Clock Polarity) and Data Order to match with SPI mode and Data Order of the other side (master device).  Finally you should enable the SPI by setting the SPIE bit of SPCR to one. 81
  • 82. Code Sequence on Slave Mode #define F_CPU 1000000UL // define crystal frequency for delay.h #include <avr/io.h> // standard AVR header #include <util/delay.h> #define SS 4 // Slave Select is Bit No.4 #define MOSI 5 // Master Out Slave In is Bit No.5 #define MISO 6 // Master In Slave Out is Bit No.6 #define SCK 7 // Shift Clock is Bit No.7 void SPI_SlaveInit(void){ DDRB |= (1<<MISO); // Set MISO as an Output Pin // Set MOSI, SCK and SS as Input Pins DDRB &= ~(1<<MOSI) & ~(1<<SCK) & ~(1<<SS) ; // Enable SPI as a Slave Device SPCR = (1<<SPE); } 82
  • 83. Code Sequence on Slave Mode unsigned char SPI_SlaveReceive(unsigned char cData){ SPDR = cData; // send cData to master // Wait for reception complete while(!(SPSR & (1<<SPIF))); // Return received data return SPDR; } 83
  • 84. Lab 1 First Clock Edge LSB goes at end 84
  • 85. MAX7221 Interfacing and Prog… 7-Segment Display:  In many applications, when you want to display numbers, 7-segments are the best choice. These displays are made of 7 LEDs to show different numbers plus another LED to display the decimal point. 85
  • 86. MAX7221 Interfacing and Prog…  If you want to connect four 7-segment LEDs directly to a microcontroller you need 4 x 8 = 32 pins. This is not feasible.  The MAX7221 IC is supports up to eight 7-segment LEDs. We can connect the MAX7221 to the AVR chip using SPI protocol and control up to eight 7-segment LEDs.  The MAX7221 contains an internal decoder that can be used to convert binary numbers to 7-segment codes. That means we do not need to refresh the 7-segment LEDs.  All you need to do is to send a binary number to the MAX7221, and the chip decodes the binary data and displays the number.  The device includes analog and digital brightness control, an 8x8 static RAM that stores each digit, and a test mode that forces all LEDs on. 86
  • 87. MAX7221 Pins and Connections  The MAX7221 is a 24-pin DIP chip. It can be directly connected to the AVR and con- trol up to eight 7-segment LEDs. A resistor or a potentiometer is the only external component that you need. Next, we will discuss the pins of the MAX7221. GND: Pin 4 and pin 9 are the ground. These should be connected to system ground Vcc: Pin 19 is the VCC and should be connected to the +5V.this pin is also the power to drive the 7-segments and the connecting wire to this pin should be able to handle 100-300 mA. 87
  • 88. MAX7221 Pins and Connections ISET: Pin 18 is ISET and sets the maximum segment current. This pin should be connected to VCC through a resistor. A 10KΩ resistor can be connected to this pin. If you want to manually control the intensity of the segments' light, you can replace the resistor with a 50KΩ potentiometer. CS :Pin 12 is the chip select pin and should be connected to the SS pin of the AVR. Serial data is loaded into the chip while CS is low, and the last 16 bits of the serial data are latched on CS's rising edge. 88
  • 89. MAX7221 Pins and Connections DIN: Pin 1 is the serial data input and should be connected to the MOSI pin of the AVR. On CLK's rising edge, data on this pin is loaded into the internal shift register. Notice that the MAX7221 uses the SPI Mode 0, that is, read on rising edge and change on falling edge.. CLK: Pin 13 is the serial clock input and should be connected to the SCK pin of the AVR. On MAX7221 the clock input is inactive when CS is high. DOUT: Pin 24 is the serial data output and is used to connect more than one MAX7221 to a single SPI bus. 89
  • 90. MAX7221 Pins and Connections DIG0-DIG7: The DIG pins are the 7-segment selector pins and should be connected to the 7-segments' common cathode pin. The MAX7221 chip can control up to eight 7-segment LEDs. These eight 7-segment dispalys are designated as DIGO to DIG7. SEGA…SEGG and DP: These pins select each segment and should be connected to segments of each 7- segment accordingly. 90
  • 91. MAX7221 data packet format  In MAX7221, data packets are 16 bits long (two bytes). You should first make CS low before transmitting; then you transmit two bytes of data and terminate the transmission by making CS high.  The first byte (MSBs) of each packet contains the command control bits, and the second byte is the data to be displayed.  The upper four bits (D15-D12) of the command byte are don't care and the lower four bits (D11-D8) are used to identify the meaning of the data byte to be followed.  The second byte (D7-D0) of the two-byte packet is called the data byte and is the actual data to be displayed or control the 7-segment driver.  Table 17-3 shows the binary and hex values of each command. 91
  • 92. MAX7221 data packet format 92
  • 93. MAX7221 data packet format 93
  • 94. 94
  • 95. 95
  • 96. MAX7221 Interfacing and Prog… #include <avr/io.h> //standard AVR header #define SS 4 #define MOSI 5 #define SCK 7 void execute (unsigned char cmd, unsigned char data){ // initializing the packet by pulling SS low PORTB &= ~(1<<SS) ; SPDR = cmd; // start CMD transmission // wait cmd transfer to finish while (!(SPSR & (1<<SPIF) ) ); // start DATA transmission SPDR = data; // wait data transfer to finish while (!(SPSR & (1<<SPIF) ) ) ; 96
  • 97. MAX7221 Interfacing and Prog… // terminate the packet by pulling SS high PORTB |= 1<<SS;} int main (void){ // MOSI, SCK and SS are output DDRB = (1<<MOSI) | (1<<SCK) | (1<<SS) ; // enable SPI as master, SCk = FOsc/16 SPCR = (1<<SPE) | (1<<MSTR)| (1<<SPR0); execute(0x09,0x03); // decode only digit 0 and 1 execute(0x0B,0x02); // Set ScanLimit(upto digit 2) execute(0x0A,0x0F); // max intensity execute(0x0C,0x01); // Turn On Display execute(0x01,0x07); // digit 0 is 7 execute(0x02,0x05); // digit 1 is 5 execute(0x03,0b00010111); // digit 2 is h while(1); return 0; } 97
  • 98. MAX7221 Interfacing and Prog… execute(0x09,0x03); 98
  • 100. SPI Vs I2C 100
  • 102. USART - Universal Synchronous and Asynchronous serial Receiver and Transmitter  Support Full Duplex mode.(two wires)  Serial interface  Used to:  Make a communication channel between our micro-controller and our computer  talk to some sensors/chips, the most used ones are serial backpacks for lcd’s and graphical lcd’s and GPS modules that use almost always an serial interface.  The serial protocol is a fairly old protocol created many years ago it was used by Teletypes and terminals 102
  • 103. THE UART INTERFACE 103 Compared to I2C, using the UART is darn-easy. UART stands for Universal Asynchronous Receive/Transmit. The hardware can also run in synchronous mode, so it is often called a USART. A good article about the hardware is at avrbeginners.net. And a good programming reference is Dean Camera’s UART article at fourwalledcubicle.com. As opposed to SPI and I2C, which are often used for binary data exchange between hardware devices, UART is often used for transmission of (slower) ASCII data. For example, you might use the UART for keyboard input or monitor/character LCD output. Speedy SPI transfers data to dedicated hardware devices at MHz speeds, while UART transfers are a thousand times slower.
  • 104. UART “Asynchronous ” frame 104 Each data frame consists of a start bit, a variable number of data bits, an optional parity bit, and 1 or 2 stop bits. The most common configuration is 1 start bit, 8 data bits, no parity bit, and 1 stop bit (“8N1”). In asynchronous mode, there is no clock line: data is transmitted on the transmit line (Tx) and received on the receive line (Rx). The UART is initialized by configuring control registers that determine the baud rate, parity, number of stop bits:
  • 106. UART on Atmega32  Features • Full Duplex Operation (Independent Serial Receive and Transmit Registers) • Asynchronous or Synchronous Operation • Master or Slave Clocked Synchronous Operation • High Resolution Baud Rate Generator • Supports Serial Frames with 5, 6, 7, 8, or 9 data bits and 1 or 2 stop bits • Odd or Even Parity Generation and Parity Check Supported by Hardware • Data OverRun Detection • Framing Error Detection • Noise Filtering Includes False Start Bit Detection and Digital Low Pass Filter • Three Separate Interrupts on TX Complete, TX Data Register Empty and RX Complete • Multi-processor Communication Mode • Double Speed Asynchronous Communication Mode 106
  • 108. Equations for Calculating Baud Rate Register Setting 108
  • 109. Examples of Baud Rate Setting 109
  • 111. UDR – USART I/O Data Register 111
  • 112. UCSRA – USART Control and Status Register A 112
  • 113. UCSRB – USART Control and Status Register B 113
  • 114. UCSRC – USART Control and Status Register C 114
  • 115. UBRRL – USART Baud Rate Register Low 115
  • 116. UBBRH – USART Baud Rate Register High 116
  • 120. MAX232 IC to convert UART to RS232 120
  • 121. FT232 (UART to USB) 121