Using The TWI Module As I2C Master
Using The TWI Module As I2C Master
Introduction
The Two-Wire Serial Interface (TWI) is compatible with Philips I2C protocol. The bus allows simple,
robust, and cost-effective communication between integrated circuits in electronics. The strengths of the
TWI bus are its capability to address up to 128 devices using the same bus and arbitration, and the
possibility to have multiple masters on the bus.
®
A hardware TWI module is included in most of the Microchip AVR devices.
This application note describes a TWI master implementation, in the form of a full-featured driver and
contains an example of usage for this driver. The driver handles transmission based on the both Standard
mode (<100kbps) and Fast mode (<400kbps).
Features
• C-code driver for TWI master
• Compatible with Philips I2C protocol
• Uses the hardware TWI module
• Interrupt driven transmission
• Supports both Standard mode and Fast mode
Table of Contents
Introduction......................................................................................................................1
Features.......................................................................................................................... 1
1. Overview....................................................................................................................3
1.1. Two-wire Serial Interface..............................................................................................................3
1.2. The AVR TWI Module...................................................................................................................4
1.2.1. Control Unit....................................................................................................................4
1.2.2. Bit Rate Generator.........................................................................................................5
1.2.3. SCL and SDA Pins........................................................................................................ 6
1.2.4. Address Match Unit....................................................................................................... 6
1.2.5. Bus Interface Unit.......................................................................................................... 7
2. Implementation.......................................................................................................... 8
2.1. Functions......................................................................................................................................8
3. Summary................................................................................................................. 12
4. Revision History.......................................................................................................13
Customer Support......................................................................................................... 14
Legal Notice...................................................................................................................15
Trademarks................................................................................................................... 15
1. Overview
This section provides a short description of the TWI interface in general and the TWI module on the AVR
8-bit Microcontroller Family. For more information, refer to the specific device datasheet.
SDA
SCL
The TWI bus is a multi-master bus where one or more devices are 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 1-2. TWI Address and Data Packet Format
Addr MSB Addr LSB R/W ACK Data MSB Data LSB ACK
SDA
SCL
1 2 7 8 9 1 2 7 8 9
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 on the Data
Direction bit, the Master or Slave now transmits 8-bit of data on the SDA line. The receiving device then
acknowledges the data. Multiple bytes can be transferred in one direction before a repeated START or
SCL SDA
Slew-rate Spike Slew-rate Spike
Control Filter Control Filter
2. Implementation
The implemented code in this application note is a pure master driver. The TWI modules also support
slave operation. See the AVR311: Using the TWI module as I2C slave application note for a sample of a
slave driver. The master and slave drivers could be merged into one combined master and slave driver,
but this is not the scope of this application note.
The master driver C-code consists of three files:
1. TWI_Master.c
2. TWI_Master.h
3. Main.c
There is an example on how to use the driver in the main.c file. The TWI_Master.h file must be
included in the main application and contains all function declarations, a define of the Bit Rate Register
(TWBR), and defines for all TWI status codes. The TWBR must be set according to the description earlier
in this application note. The TWI status code defines can be used to evaluate error messages and to take
appropriate actions. The TWI_Master.c file contains all the driver functions.
2.1 Functions
The driver consists of the TWI Interrupt Service Routine and six functions. All functions are available for
use outside the driver file scope. However, some of them are also used internally by the driver itself. All
functions in the driver are listed in the following table.
Table 2-1. Description of Functions in the TWI Master Driver
The following table consists the description of the driver register byte containing status information from
the last transceiver operation. Available as bit fields within a byte.
Table 2-2. Description of the Driver Status Register Byte
TWI_statusReg Description
TWI_statusReg.lastTransOK Set to 1 when an operation has completed successfully.
The following figure shows a flowchart of the process of sending and requesting data over the TWI
interface through the drivers. Data is passed through parameters to the functions while the status of an
operation is available trough a global status variable.
Return Return
The following figure shows a flowchart, which contains the description of TWI Driver itself . The
Transceiver function copies the complete message into the transmission buffer. Then it enables the TWI
Interrupt to initiate the transmission. The Interrupt then takes care of the complete transmission and
disables itself when the transmission is completed, or if an error state occurs. This way the driver can poll
the interrupt enable bit to check if a transmission is ongoing. The main application is only allowed to
access the global transceiver variables while the TWI transceiver is not busy. The interrupt stores
eventual error states in a variable that is available for the main application through a function call.
Figure 2-2. TWI Driver Functions
TWI Get Data From TWI Start Transceiver
TWI Get State Info TWI Interrupt
Transceiver with Data
Wait until TWI Interrupt Wait until TWI Interrupt Wait until TWI Interrupt TWI state machine
is disabled is disabled is disabled taking care of the
complete
transmission/
reception
Return ( TWI_state ) Copy transmit buffer
Transceiver No and message size, to
operation completed internal driver buffer
with success? Disables it self when
transmission completed
or error state detected
Yes Clear statusReg &
TWIstate
Return (Transceiver
operation completed with Return
success?)
The following flowchart shows a more detailed description of the actions for each event/state in the TWI
Interrupt Service Routine. The left column contains the different states/events the TWI state machine can
be in when entering the Interrupt. A case switch executes the different actions dependent on the cause of
the interrupt call.
Reset bufferPointer
Repeated START has
been transmitted
Return
3. Summary
This application note describes the steps to configure the TWI module as a Master and provides an
example driver software to implement the module. The firmware for Master Driver is available as a
download along with this application note.
4. Revision History
Doc Rev. Date Comments
®
A 07/2017 • Converted to Microchip format and replaced the Atmel document number
2564 with Microchip DS00002480
• Uploaded new updated images: TWI bus interconnection and TWI address
and Data Packet Format
• Updated the equation of "Bit rate Generation"
Microchip provides online support via our web site at http://www.microchip.com/. This web site is used as
a means to make files and information easily available to customers. Accessible by using your favorite
Internet browser, the web site contains the following information:
• Product Support – Data sheets and errata, application notes and sample programs, design
resources, user’s guides and hardware support documents, latest software releases and archived
software
• General Technical Support – Frequently Asked Questions (FAQ), technical support requests,
online discussion groups, Microchip consultant program member listing
• Business of Microchip – Product selector and ordering guides, latest Microchip press releases,
listing of seminars and events, listings of Microchip sales offices, distributors and factory
representatives
Microchip’s customer notification service helps keep customers current on Microchip products.
Subscribers will receive e-mail notification whenever there are changes, updates, revisions or errata
related to a specified product family or development tool of interest.
To register, access the Microchip web site at http://www.microchip.com/. Under “Support”, click on
“Customer Change Notification” and follow the registration instructions.
Customer Support
Note the following details of the code protection feature on Microchip devices:
• Microchip products meet the specification contained in their particular Microchip Data Sheet.
• Microchip believes that its family of products is one of the most secure families of its kind on the
market today, when used in the intended manner and under normal conditions.
• There are dishonest and possibly illegal methods used to breach the code protection feature. All of
these methods, to our knowledge, require using the Microchip products in a manner outside the
operating specifications contained in Microchip’s Data Sheets. Most likely, the person doing so is
engaged in theft of intellectual property.
• Microchip is willing to work with the customer who is concerned about the integrity of their code.
Legal Notice
Information contained in this publication regarding device applications and the like is provided only for
your convenience and may be superseded by updates. It is your responsibility to ensure that your
application meets with your specifications. MICROCHIP MAKES NO REPRESENTATIONS OR
WARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED, WRITTEN OR ORAL, STATUTORY
OR OTHERWISE, RELATED TO THE INFORMATION, INCLUDING BUT NOT LIMITED TO ITS
CONDITION, QUALITY, PERFORMANCE, MERCHANTABILITY OR FITNESS FOR PURPOSE.
Microchip disclaims all liability arising from this information and its use. Use of Microchip devices in life
support and/or safety applications is entirely at the buyer’s risk, and the buyer agrees to defend,
indemnify and hold harmless Microchip from any and all damages, claims, suits, or expenses resulting
from such use. No licenses are conveyed, implicitly or otherwise, under any Microchip intellectual
property rights unless otherwise stated.
Trademarks
The Microchip name and logo, the Microchip logo, AnyRate, AVR, AVR logo, AVR Freaks, BeaconThings,
BitCloud, CryptoMemory, CryptoRF, dsPIC, FlashFlex, flexPWR, Heldo, JukeBlox, KeeLoq, KeeLoq logo,
Kleer, LANCheck, LINK MD, maXStylus, maXTouch, MediaLB, megaAVR, MOST, MOST logo, MPLAB,
OptoLyzer, PIC, picoPower, PICSTART, PIC32 logo, Prochip Designer, QTouch, RightTouch, SAM-BA,
SpyNIC, SST, SST Logo, SuperFlash, tinyAVR, UNI/O, and XMEGA are registered trademarks of
Microchip Technology Incorporated in the U.S.A. and other countries.
ClockWorks, The Embedded Control Solutions Company, EtherSynch, Hyper Speed Control, HyperLight
Load, IntelliMOS, mTouch, Precision Edge, and Quiet-Wire are registered trademarks of Microchip
Technology Incorporated in the U.S.A.
Adjacent Key Suppression, AKS, Analog-for-the-Digital Age, Any Capacitor, AnyIn, AnyOut, BodyCom,
chipKIT, chipKIT logo, CodeGuard, CryptoAuthentication, CryptoCompanion, CryptoController,
dsPICDEM, dsPICDEM.net, Dynamic Average Matching, DAM, ECAN, EtherGREEN, In-Circuit Serial
Programming, ICSP, Inter-Chip Connectivity, JitterBlocker, KleerNet, KleerNet logo, Mindi, MiWi,
motorBench, MPASM, MPF, MPLAB Certified logo, MPLIB, MPLINK, MultiTRAK, NetDetach, Omniscient
Code Generation, PICDEM, PICDEM.net, PICkit, PICtail, PureSilicon, QMatrix, RightTouch logo, REAL
ICE, Ripple Blocker, SAM-ICE, Serial Quad I/O, SMART-I.S., SQI, SuperSwitcher, SuperSwitcher II, Total
Endurance, TSHARC, USBCheck, VariSense, ViewSpan, WiperLock, Wireless DNA, and ZENA are
trademarks of Microchip Technology Incorporated in the U.S.A. and other countries.
SQTP is a service mark of Microchip Technology Incorporated in the U.S.A.
Silicon Storage Technology is a registered trademark of Microchip Technology Inc. in other countries.
GestIC is a registered trademark of Microchip Technology Germany II GmbH & Co. KG, a subsidiary of
Microchip Technology Inc., in other countries.
All other trademarks mentioned herein are property of their respective companies.
© 2017, Microchip Technology Incorporated, Printed in the U.S.A., All Rights Reserved.
ISO/TS 16949
Microchip received ISO/TS-16949:2009 certification for its worldwide headquarters, design and wafer
fabrication facilities in Chandler and Tempe, Arizona; Gresham, Oregon and design centers in California
® ®
and India. The Company’s quality system processes and procedures are for its PIC MCUs and dsPIC
®
DSCs, KEELOQ code hopping devices, Serial EEPROMs, microperipherals, nonvolatile memory and
analog products. In addition, Microchip’s quality system for the design and manufacture of development
systems is ISO 9001:2000 certified.