Free Essay

Avr312: Using the Usi Module as a I2C Slave

In:

Submitted By sstshippy
Words 2980
Pages 12
AVR312: Using the USI module as a I2C slave
Features





C-code driver for TWI slave, with transmit and receive buffers
Compatible with Philips' I2C protocol
Interrupt driven, detection and transmission/reception
Wake up from all sleep mode, including Power Down

8-bit
Microcontrollers
Application Note

1 Introduction
The Two Wire serial Interface (TWI) is compatible with Philips' I2C protocol. The bus was developed to allow simple, robust and cost effective communication between integrated circuits in electronics. The strengths of the TWI bus includes the capability of addressing up to 128 devices on the same bus, arbitration, and the possibility to have multiple masters on the bus.
The Universal Serial Interface (USI) module on devices such as ATmega169,
ATtiny26 and ATtiny2313, has a dedicated Two-wire mode. The USI provides the basic hardware resources needed for synchronous serial communication.
Combined with a minimum of control software, the USI allows higher transfer rates and uses less code space than solutions based on software only. Interrupts are included to minimize the processor load.
This document describes how to use the USI for TWI slave communication. Source code for communication drivers for transmission and reception is provided. The code is complete with both data buffer handling and combined transmitter and receiver. Rev. 2560C-AVR-09/05

2 Theory
This section gives a short description of the TWI and USI interfaces. For more detailed information refer to the datasheets.

2.1 Two-wire serial Interface
The Two-wire Serial Interface (TWI) is ideally suited for typical microcontroller applications. The TWI protocol allows the systems designer to interconnect up to 128 individually addressable devices using only two bi-directional bus lines, one for clock
(SCL) and one for data (SDA). The only external hardware needed to implement the bus is a single pull-up resistor for each of the TWI bus lines. All devices connected to the bus have individual addresses, and mechanisms for resolving bus contention are inherent in the TWI protocol.
Figure 1. TWI Bus Interconnection
VCC

Device 1

Device 3

Device 2

........

R1

Device n

R2

SDA

SCL

The TWI bus is a multi-master bus where one or more devices, capable of taking control of the bus, can be connected. Only Master devices can drive both the SCL and SDA lines while a Slave device is only allowed to issue data on the SDA line.
Data transfer is always initiated by a Bus Master device. A high to low transition on the SDA line while SCL is high is defined to be a START condition (or a repeated start condition).
Figure 2. TWI Address and Data Packet Format
Addr LSB

Addr MSB

R/W

ACK

Data MSB

7

8

9

1

Data LSB

ACK

8

9

SDA

SCL
1

2

START

SLA+R/W

2

7
Data Byte

STOP

A START condition is always followed by the (unique) 7-bit slave address and then by a Data Direction bit. The Slave device addressed now acknowledges to the Master by holding SDA low for one clock cycle. If the Master does not receive any acknowledge the transfer is terminated. Depending of the Data Direction bit, the Master or Slave now transmits 8-bit of data on the SDA line. The receiving device then acknowledges
2

AVR312
2560C-AVR-09/05

AVR312 the data. Multiple bytes can be transferred in one direction before a repeated START or a STOP condition is issued by the Master. The transfer is terminated when the
Master issues a STOP condition. A STOP condition is defined by a low to high transition on the SDA line while the SCL is high.
If a Slave device cannot handle incoming data until it has performed some other function, it can hold SCL low to force the Master into a wait-state.
All data packets transmitted on the TWI bus are 9 bits long, consisting of one data byte and an acknowledge bit. During a data transfer, the master generates the clock and the START and STOP conditions, while the receiver is responsible for acknowledging the reception. An Acknowledge (ACK) is signaled by the receiver pulling the SDA line low during the ninth SCL cycle. If the receiver leaves the SDA line high, a NACK is signaled.

2.2 Universal Serial Interface – USI
The Universal Serial Interface (USI) provides the basic hardware resources needed for synchronous serial communication. Combined with a minimum of control software, the USI allows higher transfer rates and uses less code space than solutions based on software only. Interrupts are included to minimize the processor load. The main features of the USI are:
• Two-wire Synchronous Data Transfer
• Three-wire Synchronous Data Transfer
• Data Received Interrupt
• Wakeup from Idle Mode
• In Two-wire Mode: Wake-up from All Sleep Modes, Including Power-down Mode
• Two-wire Start Condition Detector with Interrupt Capability
The USI Two-wire mode is compliant to the TWI bus protocol, but without slew rate limiting on outputs and input noise filtering.
Figure 3. Universal Serial Interface, Block Diagram
DO

USCK/SCL

(Input/Open Drain)

Bit0

Bit7

USIPF

1
0

4-bit Counter

USIDC

USIOIF

USISIF

(Input/Open Drain)

3
2

USIDR

DATA BUS

(Output only)

DI/SDA

D Q
LE

TIM0 COMP

3
2

0
1

1
0

CLOCK
HOLD

[1]
Two-wire Clock
Control Unit

USISR

USITC

USICLK

USICS0

USICS1

USIWM0

USIWM1

USISIE

USIOIE

2

USICR

3
2560C-AVR-09/05

Figure 4. Two-wire Mode Operation, Simplified Diagram
VCC

Bit7

Bit6

Bit5

Bit4

Bit3

Bit2

Bit1

SDA

Bit0

SCL
HOLD
SCL

Two-wire Clock
Control Unit
SLAVE

Bit7

Bit6

Bit5

Bit4

Bit3

Bit2

Bit1

SDA

Bit0

SCL
PORTxn
MASTER

The USI Data Register (USIDR) is an 8-bit Shift Register that contains the incoming and outgoing data. The register has no buffering so the data must be read as quickly as possible to ensure that no data is lost.
The USI Status Register (USISR) contains a 4-bit counter. Both the Serial Register and the counter are clocked simultaneously by the same clock source. This allows the counter to count the number of bits received or transmitted and generate an interrupt when the transfer is complete. The clock can be selected to use three different sources: The SCL pin, Timer/Counter0 Compare Match or from software.
The Two-wire clock control unit can generate an interrupt when a start condition is detected on the Two-wire bus. It can also generate wait states by holding the clock pin low after a start condition is detected, or after the counter overflows.

3 Implementation
The application note describes the implementation of a TWI slave. The driver is written as a standalone driver that easily can be included into the main application.
Use the code as an example, or customize it for own use. Defines and status registers are all set in the application note header file.
The core of the driver is interrupt driven and therefore “runs in parallel” to the other processes in the application. After initializing the driver, all communication with the driver is done through a global status register variable, and the transmit and receive buffers. The size of the communication buffers can be changed in the driver header file. 4

AVR312
2560C-AVR-09/05

AVR312
Figure 5. USI TWI overview flowchart. The main code communicates with the drivers through registers and buffers.
Main code

USI TWI
Status Register
Transmit buffer
Receive buffer

Initialise USI Start
Condition Interrupt

USI Start Condition
Interrupt

USI Overflow Interrupt

Initialise USI Overflow
Interrupt
Communication mode? Communicate with
USI_TWI driver

Continue

Return

Address Mode

Master Read Data Mode

Master Write Data Mode

Return

The driver takes care of the low level communication as transmission/reception of address, data, and ACK/NACK. High level operations like address setting, message interpreting, and data preparation, must be taken care of by the main application.
When a START condition is detected the USI Start Condition Interrupt sets up the
USI Overflow Interrupt to start receiving the first package. The USI Overflow interrupt is always set to trigger after sampling 8 bits. This way the CPU is free to operate on other application specific operations during the bit sampling/transmission.
Since the USI Start Condition and USI Overflow event holds the SCL line when activated, it is not timing critical when the interrupts are to be executed. If other operations are preventing the interrupts to execute, then proper operation will still be ensured by the driver. However, to keep the communication speed on the TWI lines as high as possible the SCL time should be released a quickly as possible.
Detection of the START Condition event is always enabled. So during any state of the communication sequence, the driver will reset the reception if a USI Start Condition is detected. Any TWI message has according to the standard, an undefined length. The data to be transmitted/received needs to be held in buffers. The buffers contain all data bytes within one single message. The buffers must be read/rewritten before next the transmission. TWI address administration must be controlled from the application itself. The
USI_TWI_Slave_Initialise function takes the new address as a parameter and stores it for the driver to verify on each message reception. Rerun the initialize function to reset the address.
There are six different states gathered in three “main” states the communication can be in when entering the USI Overflow Interrupt. They are “Address Mode”, “Master
Read Data Mode”, and “Master Write Data Mode”. The states are controlled internally with the USI_TWI_state variable.

3.1 Address mode
This mode is only set the first time the USI Overflow Interrupt is executed after the
START condition is detected. The data has already been sampled into the USI data

5
2560C-AVR-09/05

register. If the address is not recognized the interface is reinitialized to wait for the next START condition, and therefore discards the rest of the message.
If it is a “general call” a bit in the status register will be set. Any actions that need to be taken based on this must be carried out by the main application.
The direction mode is read from the 8 bit in the address transmission, and is stored in the masterReadDataMode status bit, before the byte is acknowledged by the slave.
Depending on the masterReadDataMode setting, a transmission/reception is prepared before leaving the interrupt and waiting for the sampling of the next 8 bits.

3.2 Master Read Mode
Master Read Mode means that the slave has to transmit data to the master. Data is read from the transmit buffer and stored into the USI data register.
When the byte has been shifted out successfully, the slave listens for an ACK from the master. A NACK from the master is interpreted as the end of the message and tags the transmission buffer as empty, before resetting the interface.
When getting an ACK the next data byte in the buffer is put in the USI data register for transmission. Etc.

3.3 Master Write mode
Master Write Mode means that the master is going to transmit data to the slave. The
USI is set up to sample a byte on the data line.
When the byte has been shifted in successfully, the slave sends an ACK to the master. After storing the data in the buffer, and setting up USI to sample the next byte, the application waits for one USI clock to test if there has been sent a STOP condition from the master. If there is a STOP condition, the receive buffer is tagged as full. And the interface is reset. If not then the transmission is continued.

6

AVR312
2560C-AVR-09/05

AVR312
Figure 6. Flowchart of the processes in the USI Overflow Interrupt. Data buffer handling is not included here. The interrupt is initially called after 8 bits are sampled.
USI Overflow Interrupt

Adress Mode
Default start condition for new TWI pakcage. Check address and send ACK if
OK, else reset

Adress match slave adress? No

Master Write Data Mode
(Slave transmit)
USI check reply from sent data: Check the reply from sent data, start to send data or reset on NACK

NACK?

Yes

Yes

Set start condition
(reset)

No

USI send data: The USI is set to send data, and data is sent if buffer is not empty

Request or send? Data in buffer?
No

Yes
Request
USI request reply from sent data: Check reply and read
ACK

State = USI request data Set USI to read ACK

Master Read Data Mode
(Slave receive)
USI get data and send
ACK: The slave fills the buffer and sends an ACK.

Put data on buffer

Get data from buffer

State = USI request data Set USI to send data

Set USI to send
ACK

State = USI request reply from sent data

Set USI to send ACK

USI request data:Prepares the slave for reading data

Send

Set start condition
(reset)

State = USI check reply from sent data

State = USI send data State = USI get data and send ACK

Set USI to read data

Return

These actions will terminate and reset any transmission:







The address in the message is not zero, nor the defined TWI address.
The master returns a NACK on a slave transmission.
The master sends a STOP Condition, after the slave sends a ACK.
The master sends a START Condition.
The master requests data, but the transmit buffer is empty.
The master sends data, but the receive buffer is full.

7
2560C-AVR-09/05

Optionally one can also add more buffer control and the same response if the master requests/sends more information then the size of the transmit/receive buffers. This buffer control can be enabled by setting a define in the driver header file.

3.4 Sleep modes
The USI Start Condition is able to wake up the AVR from all sleep modes including
Power Down. The device must however stay in active mode until the complete message has been received/transmitted.

3.5 Code size
The code coming with this application note was compiled using IAR Embedded
Workbench V 4.11A with full optimization, giving a total size of 398 bytes. The code contains an optional debug routine..
Table 1. Code sizes with IAR EWAVR 4.11A with all code optimization on
Function

Size [bytes]

Flush_TWI_Buffers

14

USI_TWI_Slave_Initialise( )

26

USI_TWI_Transmit_Byte( )

34

USI_TWI_Receive_Byte( )

28

USI_TWI_Data_In_Receive_Buffer( )

18

USI_Start_Condition_ISR( )

24

USI_Counter_Overflow_ISR( )

220
364

8

AVR312
2560C-AVR-09/05

Disclaimer

Atmel Corporation
2325 Orchard Parkway
San Jose, CA 95131, USA
Tel: 1(408) 441-0311
Fax: 1(408) 487-2600

Regional Headquarters
Europe
Atmel Sarl
Route des Arsenaux 41
Case Postale 80
CH-1705 Fribourg
Switzerland
Tel: (41) 26-426-5555
Fax: (41) 26-426-5500

Asia
Room 1219
Chinachem Golden Plaza
77 Mody Road Tsimshatsui
East Kowloon
Hong Kong
Tel: (852) 2721-9778
Fax: (852) 2722-1369

Japan
9F, Tonetsu Shinkawa Bldg.
1-24-8 Shinkawa
Chuo-ku, Tokyo 104-0033
Japan
Tel: (81) 3-3523-3551
Fax: (81) 3-3523-7581

Atmel Operations
Memory
2325 Orchard Parkway
San Jose, CA 95131, USA
Tel: 1(408) 441-0311
Fax: 1(408) 436-4314

Microcontrollers
2325 Orchard Parkway
San Jose, CA 95131, USA
Tel: 1(408) 441-0311
Fax: 1(408) 436-4314
La Chantrerie
BP 70602
44306 Nantes Cedex 3, France
Tel: (33) 2-40-18-18-18
Fax: (33) 2-40-18-19-60

ASIC/ASSP/Smart Cards
Zone Industrielle
13106 Rousset Cedex, France
Tel: (33) 4-42-53-60-00
Fax: (33) 4-42-53-60-01

RF/Automotive
Theresienstrasse 2
Postfach 3535
74025 Heilbronn, Germany
Tel: (49) 71-31-67-0
Fax: (49) 71-31-67-2340
1150 East Cheyenne Mtn. Blvd.
Colorado Springs, CO 80906, USA
Tel: 1(719) 576-3300
Fax: 1(719) 540-1759

Biometrics/Imaging/Hi-Rel MPU/
High Speed Converters/RF Datacom
Avenue de Rochepleine
BP 123
38521 Saint-Egreve Cedex, France
Tel: (33) 4-76-58-30-00
Fax: (33) 4-76-58-34-80

1150 East Cheyenne Mtn. Blvd.
Colorado Springs, CO 80906, USA
Tel: 1(719) 576-3300
Fax: 1(719) 540-1759
Scottish Enterprise Technology Park
Maxwell Building
East Kilbride G75 0QR, Scotland
Tel: (44) 1355-803-000
Fax: (44) 1355-242-743

Literature Requests www.atmel.com/literature Disclaimer: The information in this document is provided in connection with Atmel products. No license, express or implied, by estoppel or otherwise, to any intellectual property right is granted by this document or in connection with the sale of Atmel products. EXCEPT AS SET FORTH IN ATMEL’S TERMS AND
CONDITIONS OF SALE LOCATED ON ATMEL’S WEB SITE, ATMEL ASSUMES NO LIABILITY WHATSOEVER AND DISCLAIMS ANY EXPRESS, IMPLIED
OR STATUTORY WARRANTY RELATING TO ITS PRODUCTS INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTY OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT,
CONSEQUENTIAL, PUNITIVE, SPECIAL OR INCIDENTAL DAMAGES (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF PROFITS, BUSINESS
INTERRUPTION, OR LOSS OF INFORMATION) ARISING OUT OF THE USE OR INABILITY TO USE THIS DOCUMENT, EVEN IF ATMEL HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Atmel makes no representations or warranties with respect to the accuracy or completeness of the contents of this document and reserves the right to make changes to specifications and product descriptions at any time without notice. Atmel does not make any commitment to update the information contained herein. Unless specifically provided otherwise, Atmel products are not suitable for, and shall not be used in, automotive applications. Atmel’s products are not intended, authorized, or warranted for use as components in applications intended to support or sustain life.

© Atmel Corporation 2005. All rights reserved. Atmel®, logo and combinations thereof, Everywhere You Are®, AVR®, AVR Studio® and others, are the registered trademarks or trademarks of Atmel Corporation or its subsidiaries. Other terms and product names may be trademarks of others.

2560C-AVR-09/05

Similar Documents