\hypertarget{group__twi__demo}{}\doxysubsection{Example using the two-\/wire interface (T\+WI)}
\label{group__twi__demo}\index{Example using the two-\/wire interface (TWI)@{Example using the two-\/wire interface (TWI)}}
Some newer devices of the A\+Tmega series contain builtin support for interfacing the microcontroller to a two-\/wire bus, called T\+WI. This is essentially the same called I2C by Philips, but that term is avoided in Atmel\textquotesingle{}s documentation due to patenting issues.

For further documentation, see\+:

\href{http://www.nxp.com/documents/user_manual/UM10204.pdf}{\texttt{ http\+://www.\+nxp.\+com/documents/user\+\_\+manual/\+U\+M10204.\+pdf}}\hypertarget{group__twi__demo_twi_demo_intro}{}\doxysubsubsection{Introduction into T\+WI}\label{group__twi__demo_twi_demo_intro}
The two-\/wire interface consists of two signal lines named {\itshape S\+DA} (serial data) and {\itshape S\+CL} (serial clock) (plus a ground line, of course). All devices participating in the bus are connected together, using open-\/drain driver circuitry, so the wires must be terminated using appropriate pullup resistors. The pullups must be small enough to recharge the line capacity in short enough time compared to the desired maximal clock frequency, yet large enough so all drivers will not be overloaded. There are formulas in the datasheet that help selecting the pullups.

Devices can either act as a master to the bus (i. e., they initiate a transfer), or as a slave (they only act when being called by a master). The bus is multi-\/master capable, and a particular device implementation can act as either master or slave at different times. Devices are addressed using a 7-\/bit address (coordinated by Philips) transfered as the first byte after the so-\/called start condition. The L\+SB of that byte is R/$\sim$W, i. e. it determines whether the request to the slave is to read or write data during the next cycles. (There is also an option to have devices using 10-\/bit addresses but that is not covered by this example.)\hypertarget{group__twi__demo_twi_demo_project}{}\doxysubsubsection{The T\+W\+I example project}\label{group__twi__demo_twi_demo_project}
The A\+Tmega T\+WI hardware supports both, master and slave operation. This example will only demonstrate how to use an A\+VR microcontroller as T\+WI master. The implementation is kept simple in order to concentrate on the steps that are required to talk to a T\+WI slave, so all processing is done in polled-\/mode, waiting for the T\+WI interface to indicate that the next processing step is due (by setting the T\+W\+I\+NT interrupt bit). If it is desired to have the entire T\+WI communication happen in \char`\"{}background\char`\"{}, all this can be implemented in an interrupt-\/controlled way, where only the start condition needs to be triggered from outside the interrupt routine.

There is a variety of slave devices available that can be connected to a T\+WI bus. For the purpose of this example, an E\+E\+P\+R\+OM device out of the industry-\/standard {\bfseries{24C{\itshape xx}}} series has been chosen (where {\itshape xx} can be one of {\bfseries{01}}, {\bfseries{02}}, {\bfseries{04}}, {\bfseries{08}}, or {\bfseries{16}}) which are available from various vendors. The choice was almost arbitrary, mainly triggered by the fact that an E\+E\+P\+R\+OM device is being talked to in both directions, reading and writing the slave device, so the example will demonstrate the details of both.

Usually, there is probably not much need to add more E\+E\+P\+R\+OM to an A\+Tmega system that way\+: the smallest possible A\+VR device that offers hardware T\+WI support is the A\+Tmega8 which comes with 512 bytes of E\+E\+P\+R\+OM, which is equivalent to an 24C04 device. The A\+Tmega128 already comes with twice as much E\+E\+P\+R\+OM as the 24C16 would offer. One exception might be to use an externally connected E\+E\+P\+R\+OM device that is removable; e. g. S\+D\+R\+AM PC memory comes with an integrated T\+WI E\+E\+P\+R\+OM that carries the R\+AM configuration information.\hypertarget{group__twi__demo_twi_demo_src}{}\doxysubsubsection{The Source Code}\label{group__twi__demo_twi_demo_src}


 
The source code is installed under

\texttt{\$prefix/share/doc/avr-libc/examples/twitest/twitest.c},

where \texttt{\$prefix} is a configuration option.  For Unix
systems, it is usually set to either \texttt{/usr} or
\texttt{/usr/local}.


\begin{DoxyParagraph}{Note \mbox{[}1\mbox{]}}

\end{DoxyParagraph}
The header file {\ttfamily $<$\mbox{\hyperlink{util_2twi_8h}{util/twi.\+h}}$>$} contains some macro definitions for symbolic constants used in the T\+WI status register. These definitions match the names used in the Atmel datasheet except that all names have been prefixed with {\ttfamily T\+W\+\_\+}.

\begin{DoxyParagraph}{Note \mbox{[}2\mbox{]}}

\end{DoxyParagraph}
The clock is used in timer calculations done by the compiler, for the U\+A\+RT baud rate and the T\+WI clock rate.

\begin{DoxyParagraph}{Note \mbox{[}3\mbox{]}}

\end{DoxyParagraph}
The address assigned for the 24Cxx E\+E\+P\+R\+OM consists of 1010 in the upper four bits. The following three bits are normally available as slave sub-\/addresses, allowing to operate more than one device of the same type on a single bus, where the actual subaddress used for each device is configured by hardware strapping. However, since the next data packet following the device selection only allows for 8 bits that are used as an E\+E\+P\+R\+OM address, devices that require more than 8 address bits (24C04 and above) \char`\"{}steal\char`\"{} subaddress bits and use them for the E\+E\+P\+R\+OM cell address bits 9 to 11 as required. This example simply assumes all subaddress bits are 0 for the smaller devices, so the E0, E1, and E2 inputs of the 24Cxx must be grounded.

\begin{DoxyParagraph}{Note \mbox{[}3a\mbox{]}}

\end{DoxyParagraph}
E\+E\+P\+R\+O\+Ms of type 24C32 and above cannot be addressed anymore even with the subaddress bit trick. Thus, they require the upper address bits being sent separately on the bus. When activating the {\ttfamily W\+O\+R\+D\+\_\+\+A\+D\+D\+R\+E\+S\+S\+\_\+16\+B\+IT} define, the algorithm implements that auxiliary address byte transmission.

\begin{DoxyParagraph}{Note \mbox{[}4\mbox{]}}

\end{DoxyParagraph}
For slow clocks, enable the 2 x U\mbox{[}S\mbox{]}A\+RT clock multiplier, to improve the baud rate error. This will allow a 9600 Bd communication using the standard 1 M\+Hz calibrated RC oscillator. See also the Baud rate tables in the datasheets.

\begin{DoxyParagraph}{Note \mbox{[}5\mbox{]}}

\end{DoxyParagraph}
The datasheet explains why a minimum T\+W\+BR value of 10 should be maintained when running in master mode. Thus, for system clocks below 3.\+6 M\+Hz, we cannot run the bus at the intented clock rate of 100 k\+Hz but have to slow down accordingly.

\begin{DoxyParagraph}{Note \mbox{[}6\mbox{]}}

\end{DoxyParagraph}
This function is used by the standard output facilities that are utilized in this example for debugging and demonstration purposes.

\begin{DoxyParagraph}{Note \mbox{[}7\mbox{]}}

\end{DoxyParagraph}
In order to shorten the data to be sent over the T\+WI bus, the 24Cxx E\+E\+P\+R\+O\+Ms support multiple data bytes transfered within a single request, maintaining an internal address counter that is updated after each data byte transfered successfully. When reading data, one request can read the entire device memory if desired (the counter would wrap around and start back from 0 when reaching the end of the device).

\begin{DoxyParagraph}{Note \mbox{[}8\mbox{]}}

\end{DoxyParagraph}
When reading the E\+E\+P\+R\+OM, a first device selection must be made with write intent (R/$\sim$W bit set to 0 indicating a write operation) in order to transfer the E\+E\+P\+R\+OM address to start reading from. This is called {\itshape master transmitter mode}. Each completion of a particular step in T\+WI communication is indicated by an asserted T\+W\+I\+NT bit in T\+W\+CR. (An interrupt would be generated if allowed.) After performing any actions that are needed for the next communication step, the interrupt condition must be manually cleared by {\itshape setting} the T\+W\+I\+NT bit. Unlike with many other interrupt sources, this would even be required when using a true interrupt routine, since as soon as T\+W\+I\+NT is re-\/asserted, the next bus transaction will start.

\begin{DoxyParagraph}{Note \mbox{[}9\mbox{]}}

\end{DoxyParagraph}
Since the T\+WI bus is multi-\/master capable, there is potential for a bus contention when one master starts to access the bus. Normally, the T\+WI bus interface unit will detect this situation, and will not initiate a start condition while the bus is busy. However, in case two masters were starting at exactly the same time, the way bus arbitration works, there is always a chance that one master could lose arbitration of the bus during any transmit operation. A master that has lost arbitration is required by the protocol to immediately cease talking on the bus; in particular it must not initiate a stop condition in order to not corrupt the ongoing transfer from the active master. In this example, upon detecting a lost arbitration condition, the entire transfer is going to be restarted. This will cause a new start condition to be initiated, which will normally be delayed until the currently active master has released the bus.

\begin{DoxyParagraph}{Note \mbox{[}10\mbox{]}}

\end{DoxyParagraph}
Next, the device slave is going to be reselected (using a so-\/called repeated start condition which is meant to guarantee that the bus arbitration will remain at the current master) using the same slave address (S\+LA), but this time with read intent (R/$\sim$W bit set to 1) in order to request the device slave to start transfering data from the slave to the master in the next packet.

\begin{DoxyParagraph}{Note \mbox{[}11\mbox{]}}

\end{DoxyParagraph}
If the E\+E\+P\+R\+OM device is still busy writing one or more cells after a previous write request, it will simply leave its bus interface drivers at high impedance, and does not respond to a selection in any way at all. The master selecting the device will see the high level at S\+DA after transfering the S\+L\+A+\+R/W packet as a N\+A\+CK to its selection request. Thus, the select process is simply started over (effectively causing a {\itshape repeated start condition}), until the device will eventually respond. This polling procedure is recommended in the 24Cxx datasheet in order to minimize the busy wait time when writing. Note that in case a device is broken and never responds to a selection (e. g. since it is no longer present at all), this will cause an infinite loop. Thus the maximal number of iterations made until the device is declared to be not responding at all, and an error is returned, will be limited to M\+A\+X\+\_\+\+I\+T\+ER.

\begin{DoxyParagraph}{Note \mbox{[}12\mbox{]}}

\end{DoxyParagraph}
This is called {\itshape master receiver mode}\+: the bus master still supplies the S\+CL clock, but the device slave drives the S\+DA line with the appropriate data. After 8 data bits, the master responds with an A\+CK bit (S\+DA driven low) in order to request another data transfer from the slave, or it can leave the S\+DA line high (N\+A\+CK), indicating to the slave that it is going to stop the transfer now. Assertion of A\+CK is handled by setting the T\+W\+EA bit in T\+W\+CR when starting the current transfer.

\begin{DoxyParagraph}{Note \mbox{[}13\mbox{]}}

\end{DoxyParagraph}
The control word sent out in order to initiate the transfer of the next data packet is initially set up to assert the T\+W\+EA bit. During the last loop iteration, T\+W\+EA is de-\/asserted so the client will get informed that no further transfer is desired.

\begin{DoxyParagraph}{Note \mbox{[}14\mbox{]}}

\end{DoxyParagraph}
Except in the case of lost arbitration, all bus transactions must properly be terminated by the master initiating a stop condition.

\begin{DoxyParagraph}{Note \mbox{[}15\mbox{]}}

\end{DoxyParagraph}
Writing to the E\+E\+P\+R\+OM device is simpler than reading, since only a master transmitter mode transfer is needed. Note that the first packet after the S\+L\+A+W selection is always considered to be the E\+E\+P\+R\+OM address for the next operation. (This packet is exactly the same as the one above sent before starting to read the device.) In case a master transmitter mode transfer is going to send more than one data packet, all following packets will be considered data bytes to write at the indicated address. The internal address pointer will be incremented after each write operation.

\begin{DoxyParagraph}{Note \mbox{[}16\mbox{]}}

\end{DoxyParagraph}
24Cxx devices can become write-\/protected by strapping their $\sim$\+WC pin to logic high. (Leaving it unconnected is explicitly allowed, and constitutes logic low level, i. e. no write protection.) In case of a write protected device, all data transfer attempts will be N\+A\+C\+Ked by the device. Note that some devices might not implement this. 