# Example using the two-wire interface (TWI)
[Demo projects]

Some newer devices of the ATmega series contain builtin support for interfacing the microcontroller to a two-wire bus, called TWI. This is essentially the same called I2C by Philips, but that term is avoided in Atmel's documentation due to patenting issues.

For the original Philips documentation, see

http://www.semiconductors.philips.com/buses/i2c/index.html

## Introduction into TWI

The two-wire interface consists of two signal lines named SDA (serial data) and SCL (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 LSB of that byte is R/~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.)

## The TWI example project

The ATmega TWI hardware supports both, master and slave operation. This example will only demonstrate how to use an AVR microcontroller as TWI master. The implementation is kept simple in order to concentrate on the steps that are required to talk to a TWI slave, so all processing is done in polled-mode, waiting for the TWI interface to indicate that the next processing step is due (by setting the TWINT interrupt bit). If it is desired to have the entire TWI communication happen in "background", 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 TWI bus. For the purpose of this example, an EEPROM device out of the industry-standard 24Cxx series has been chosen (where xx can be one of 01, 02, 04, 08, or 16) which are available from various vendors. The choice was almost arbitrary, mainly triggered by the fact that an EEPROM 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 EEPROM to an ATmega system that way: the smallest possible AVR device that offers hardware TWI support is the ATmega8 which comes with 512 bytes of EEPROM, which is equivalent to an 24C04 device. The ATmega128 already comes with twice as much EEPROM as the 24C16 would offer. One exception might be to use an externally connected EEPROM device that is removable; e. g. SDRAM PC memory comes with an integrated TWI EEPROM that carries the RAM configuration information.

## The Source Code

    /*
     * ----------------------------------------------------------------------------
     * "THE BEER-WARE LICENSE" (Revision 42):
     * <joerg@FreeBSD.ORG> wrote this file.  As long as you retain this notice you
     * can do whatever you want with this stuff. If we meet some day, and you think
     * this stuff is worth it, you can buy me a beer in return.        Joerg Wunsch
     * ----------------------------------------------------------------------------
     */

    /* $Id: twitest.c,v 1.2.2.2 2005/02/07 22:47:46 arcanum Exp $ */

    /*
     * Simple demo program that talks to a 24Cxx I²C EEPROM using the
     * builtin TWI interface of an ATmega device.
     */

    #include <inttypes.h>
    #include <stdio.h>
    #include <stdlib.h>

    #include <avr/io.h>
    #include <compat/twi.h>         /* Note [1] */

    #define DEBUG 1

    /*
     * System clock in Hz.
     */
    #define F_CPU 14745600UL        /* Note [2] */

    /*
     * Compatibility defines.  This should work on ATmega8, ATmega16,
     * ATmega163, ATmega323 and ATmega128 (IOW: on all devices that
     * provide a builtin TWI interface).
     *
     * On the 128, it defaults to USART 1.
     */
    #ifndef UCSRB
    # ifdef UCSR1A          /* ATmega128 */
    #  define UCSRA UCSR1A
    #  define UCSRB UCSR1B
    #  define UBRR UBRR1L
    #  define UDR UDR1
    # else /* ATmega8 */
    #  define UCSRA USR
    #  define UCSRB UCR
    # endif
    #endif
    #ifndef UBRR
    #  define UBRR UBRRL
    #endif

    /*
     * Note [3]
     * TWI address for 24Cxx EEPROM:
     *
     * 1 0 1 0 E2 E1 E0 R/~W        24C01/24C02
     * 1 0 1 0 E2 E1 A8 R/~W        24C04
     * 1 0 1 0 E2 A9 A8 R/~W        24C08
     * 1 0 1 0 A10 A9 A8 R/~W       24C16
     */
    #define TWI_SLA_24CXX   0xa0    /* E2 E1 E0 = 0 0 0 */

    /*
     * Maximal number of iterations to wait for a device to respond for a
     * selection.  Should be large enough to allow for a pending write to
     * complete, but low enough to properly abort an infinite loop in case
     * a slave is broken or not present at all.  With 100 kHz TWI clock,
     * transfering the start condition and SLA+R/W packet takes about 10
     * µs.  The longest write period is supposed to not exceed ~ 10 ms.
     * Thus, normal operation should not require more than 100 iterations
     * to get the device to respond to a selection.
     */
    #define MAX_ITER        200

    /*
     * Number of bytes that can be written in a row, see comments for
     * ee24xx_write_page() below.  Some vendor's devices would accept 16,
     * but 8 seems to be the lowest common denominator.
     *
     * Note that the page size must be a power of two, this simplifies the
     * page boundary calculations below.
     */
    #define PAGE_SIZE 8

    /*
     * Saved TWI status register, for error messages only.  We need to
     * save it in a variable, since the datasheet only guarantees the TWSR
     * register to have valid contents while the TWINT bit in TWCR is set.
     */
    uint8_t twst;

    /*
     * Do all the startup-time peripheral initializations: UART (for our
     * debug/test output), and TWI clock.
     */
    void
    ioinit(void)
    {

    #if F_CPU <= 1000000UL
      /*
       * Note [4]
       * Slow system clock, double Baud rate to improve rate error.
       */
      UCSRA = _BV(U2X);
      UBRR = (F_CPU / (8 * 9600UL)) - 1; /* 9600 Bd */
    #else
      UBRR = (F_CPU / (16 * 9600UL)) - 1; /* 9600 Bd */
    #endif
      UCSRB = _BV(TXEN);            /* tx enable */

      /* initialize TWI clock: 100 kHz clock, TWPS = 0 => prescaler = 1 */
    #if defined(TWPS0)
      /* has prescaler (mega128 & newer) */
      TWSR = 0;
    #endif

    #if F_CPU < 3600000UL
      TWBR = 10;                    /* smallest TWBR value, see note [5] */
    #else
      TWBR = (F_CPU / 100000UL - 16) / 2;
    #endif
    }

    /*
     * Note [6]
     * Send character c down the UART Tx, wait until tx holding register
     * is empty.
     */
    int
    uart_putchar(char c)
    {

      if (c == '\n')
        uart_putchar('\r');
      loop_until_bit_is_set(UCSRA, UDRE);
      UDR = c;
      return 0;
    }

    /*
     * Note [7]
     *
     * Read "len" bytes from EEPROM starting at "eeaddr" into "buf".
     *
     * This requires two bus cycles: during the first cycle, the device
     * will be selected (master transmitter mode), and the address
     * transfered.  Address bits exceeding 256 are transfered in the
     * E2/E1/E0 bits (subaddress bits) of the device selector.
     *
     * The second bus cycle will reselect the device (repeated start
     * condition, going into master receiver mode), and transfer the data
     * from the device to the TWI master.  Multiple bytes can be
     * transfered by ACKing the client's transfer.  The last transfer will
     * be NACKed, which the client will take as an indication to not
     * initiate further transfers.
     */
    int
    ee24xx_read_bytes(uint16_t eeaddr, int len, uint8_t *buf)
    {
      uint8_t sla, twcr, n = 0;
      int rv = 0;

      /* patch high bits of EEPROM address into SLA */
      sla = TWI_SLA_24CXX | (((eeaddr >> 8) & 0x07) << 1);

      /*
       * Note [8]
       * First cycle: master transmitter mode
       */
      restart:
      if (n++ >= MAX_ITER)
        return -1;
      begin:

      TWCR = _BV(TWINT) | _BV(TWSTA) | _BV(TWEN); /* send start condition */
      while ((TWCR & _BV(TWINT)) == 0) ; /* wait for transmission */
      switch ((twst = TW_STATUS))
        {
        case TW_REP_START:          /* OK, but should not happen */
        case TW_START:
          break;

        case TW_MT_ARB_LOST:        /* Note [9] */
          goto begin;

        default:
          return -1;                /* error: not in start condition */
                                    /* NB: do /not/ send stop condition */
        }

      /* Note [10] */
      /* send SLA+W */
      TWDR = sla | TW_WRITE;
      TWCR = _BV(TWINT) | _BV(TWEN); /* clear interrupt to start transmission */
      while ((TWCR & _BV(TWINT)) == 0) ; /* wait for transmission */
      switch ((twst = TW_STATUS))
        {
        case TW_MT_SLA_ACK:
          break;

        case TW_MT_SLA_NACK:        /* nack during select: device busy writing */
                                    /* Note [11] */
          goto restart;

        case TW_MT_ARB_LOST:        /* re-arbitrate */
          goto begin;

        default:
          goto error;               /* must send stop condition */
        }

      TWDR = eeaddr;                /* low 8 bits of addr */
      TWCR = _BV(TWINT) | _BV(TWEN); /* clear interrupt to start transmission */
      while ((TWCR & _BV(TWINT)) == 0) ; /* wait for transmission */
      switch ((twst = TW_STATUS))
        {
        case TW_MT_DATA_ACK:
          break;

        case TW_MT_DATA_NACK:
          goto quit;

        case TW_MT_ARB_LOST:
          goto begin;

        default:
          goto error;               /* must send stop condition */
        }

      /*
       * Note [12]
       * Next cycle(s): master receiver mode
       */
      TWCR = _BV(TWINT) | _BV(TWSTA) | _BV(TWEN); /* send (rep.) start condition */
      while ((TWCR & _BV(TWINT)) == 0) ; /* wait for transmission */
      switch ((twst = TW_STATUS))
        {
        case TW_START:              /* OK, but should not happen */
        case TW_REP_START:
          break;

        case TW_MT_ARB_LOST:
          goto begin;

        default:
          goto error;
        }

      /* send SLA+R */
      TWDR = sla | TW_READ;
      TWCR = _BV(TWINT) | _BV(TWEN); /* clear interrupt to start transmission */
      while ((TWCR & _BV(TWINT)) == 0) ; /* wait for transmission */
      switch ((twst = TW_STATUS))
        {
        case TW_MR_SLA_ACK:
          break;

        case TW_MR_SLA_NACK:
          goto quit;

        case TW_MR_ARB_LOST:
          goto begin;

        default:
          goto error;
        }

      for (twcr = _BV(TWINT) | _BV(TWEN) | _BV(TWEA) /* Note [13] */;
           len > 0;
           len--)
        {
          if (len == 1)
            twcr = _BV(TWINT) | _BV(TWEN); /* send NAK this time */
          TWCR = twcr;              /* clear int to start transmission */
          while ((TWCR & _BV(TWINT)) == 0) ; /* wait for transmission */
          switch ((twst = TW_STATUS))
            {
            case TW_MR_DATA_NACK:
              len = 0;              /* force end of loop */
              /* FALLTHROUGH */
            case TW_MR_DATA_ACK:
              *buf++ = TWDR;
              rv++;
              break;

            default:
              goto error;
            }
        }
      quit:
      /* Note [14] */
      TWCR = _BV(TWINT) | _BV(TWSTO) | _BV(TWEN); /* send stop condition */

      return rv;

      error:
      rv = -1;
      goto quit;
    }

    /*
     * Write "len" bytes into EEPROM starting at "eeaddr" from "buf".
     *
     * This is a bit simpler than the previous function since both, the
     * address and the data bytes will be transfered in master transmitter
     * mode, thus no reselection of the device is necessary.  However, the
     * EEPROMs are only capable of writing one "page" simultaneously, so
     * care must be taken to not cross a page boundary within one write
     * cycle.  The amount of data one page consists of varies from
     * manufacturer to manufacturer: some vendors only use 8-byte pages
     * for the smaller devices, and 16-byte pages for the larger devices,
     * while other vendors generally use 16-byte pages.  We thus use the
     * smallest common denominator of 8 bytes per page, declared by the
     * macro PAGE_SIZE above.
     *
     * The function simply returns after writing one page, returning the
     * actual number of data byte written.  It is up to the caller to
     * re-invoke it in order to write further data.
     */
    int
    ee24xx_write_page(uint16_t eeaddr, int len, uint8_t *buf)
    {
      uint8_t sla, n = 0;
      int rv = 0;
      uint16_t endaddr;

      if (eeaddr + len < (eeaddr | (PAGE_SIZE - 1)))
        endaddr = eeaddr + len;
      else
        endaddr = (eeaddr | (PAGE_SIZE - 1)) + 1;
      len = endaddr - eeaddr;

      /* patch high bits of EEPROM address into SLA */
      sla = TWI_SLA_24CXX | (((eeaddr >> 8) & 0x07) << 1);

      restart:
      if (n++ >= MAX_ITER)
        return -1;
      begin:

      /* Note [15] */
      TWCR = _BV(TWINT) | _BV(TWSTA) | _BV(TWEN); /* send start condition */
      while ((TWCR & _BV(TWINT)) == 0) ; /* wait for transmission */
      switch ((twst = TW_STATUS))
        {
        case TW_REP_START:          /* OK, but should not happen */
        case TW_START:
          break;

        case TW_MT_ARB_LOST:
          goto begin;

        default:
          return -1;                /* error: not in start condition */
                                    /* NB: do /not/ send stop condition */
        }

      /* send SLA+W */
      TWDR = sla | TW_WRITE;
      TWCR = _BV(TWINT) | _BV(TWEN); /* clear interrupt to start transmission */
      while ((TWCR & _BV(TWINT)) == 0) ; /* wait for transmission */
      switch ((twst = TW_STATUS))
        {
        case TW_MT_SLA_ACK:
          break;

        case TW_MT_SLA_NACK:        /* nack during select: device busy writing */
          goto restart;

        case TW_MT_ARB_LOST:        /* re-arbitrate */
          goto begin;

        default:
          goto error;               /* must send stop condition */
        }

      TWDR = eeaddr;                /* low 8 bits of addr */
      TWCR = _BV(TWINT) | _BV(TWEN); /* clear interrupt to start transmission */
      while ((TWCR & _BV(TWINT)) == 0) ; /* wait for transmission */
      switch ((twst = TW_STATUS))
        {
        case TW_MT_DATA_ACK:
          break;

        case TW_MT_DATA_NACK:
          goto quit;

        case TW_MT_ARB_LOST:
          goto begin;

        default:
          goto error;               /* must send stop condition */
        }

      for (; len > 0; len--)
        {
          TWDR = *buf++;
          TWCR = _BV(TWINT) | _BV(TWEN); /* start transmission */
          while ((TWCR & _BV(TWINT)) == 0) ; /* wait for transmission */
          switch ((twst = TW_STATUS))
            {
            case TW_MT_DATA_NACK:
              goto error;           /* device write protected -- Note [16] */

            case TW_MT_DATA_ACK:
              rv++;
              break;

            default:
              goto error;
            }
        }
      quit:
      TWCR = _BV(TWINT) | _BV(TWSTO) | _BV(TWEN); /* send stop condition */

      return rv;

      error:
      rv = -1;
      goto quit;
    }

    /*
     * Wrapper around ee24xx_write_page() that repeats calling this
     * function until either an error has been returned, or all bytes
     * have been written.
     */
    int
    ee24xx_write_bytes(uint16_t eeaddr, int len, uint8_t *buf)
    {
      int rv, total;

      total = 0;
      do
        {
    #if DEBUG
          printf("Calling ee24xx_write_page(%d, %d, %p)",
                 eeaddr, len, buf);
    #endif
          rv = ee24xx_write_page(eeaddr, len, buf);
    #if DEBUG
          printf(" => %d\n", rv);
    #endif
          if (rv == -1)
            return -1;
          eeaddr += rv;
          len -= rv;
          buf += rv;
          total += rv;
        }
      while (len > 0);

      return total;
    }

    void
    error(void)
    {

      printf("error: TWI status %#x\n", twst);
      exit(0);
    }

    void
    main(void)
    {
      uint16_t a;
      int rv;
      uint8_t b[16];
      uint8_t x;

      ioinit();

      fdevopen(uart_putchar, NULL, 0);

      for (a = 0; a < 256;)
        {
          printf("%#04x: ", a);
          rv = ee24xx_read_bytes(a, 16, b);
          if (rv <= 0)
            error();
          if (rv < 16)
            printf("warning: short read %d\n", rv);
          a += rv;
          for (x = 0; x < rv; x++)
            printf("%02x ", b[x]);
          putchar('\n');
        }
    #define EE_WRITE(addr, str) ee24xx_write_bytes(addr, sizeof(str)-1, str)
      rv = EE_WRITE(55, "The quick brown fox jumps over the lazy dog.");
      if (rv < 0)
        error();
      printf("Wrote %d bytes.\n", rv);
      for (a = 0; a < 256;)
        {
          printf("%#04x: ", a);
          rv = ee24xx_read_bytes(a, 16, b);
          if (rv <= 0)
            error();
          if (rv < 16)
            printf("warning: short read %d\n", rv);
          a += rv;
          for (x = 0; x < rv; x++)
            printf("%02x ", b[x]);
          putchar('\n');
        }

      printf("done.\n");

    }

Note [1]

The header file `<compat/twi.h>` contains some macro definitions for symbolic constants used in the TWI status register. These definitions match the names used in the Atmel datasheet except that all names have been prefixed with `TW_`.

Note [2]

The clock is used in timer calculations done by the compiler, for the UART baud rate and the TWI clock rate.

Note [3]

The address assigned for the 24Cxx EEPROM 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 EEPROM address, devices that require more than 8 address bits (24C04 and above) "steal" subaddress bits and use them for the EEPROM 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.

Note [4]

For slow clocks, enable the 2 x U[S]ART clock multiplier, to improve the baud rate error. This will allow a 9600 Bd communication using the standard 1 MHz calibrated RC oscillator. See also the Baud rate tables in the datasheets.

Note [5]

The datasheet explains why a minimum TWBR value of 10 should be maintained when running in master mode. Thus, for system clocks below 3.6 MHz, we cannot run the bus at the intented clock rate of 100 kHz but have to slow down accordingly.

Note [6]

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

Note [7]

In order to shorten the data to be sent over the TWI bus, the 24Cxx EEPROMs 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).

Note [8]

When reading the EEPROM, a first device selection must be made with write intent (R/~W bit set to 0 indicating a write operation) in order to transfer the EEPROM address to start reading from. This is called master transmitter mode. Each completion of a particular step in TWI communication is indicated by an asserted TWINT bit in TWCR. (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 setting the TWINT bit. Unlike with many other interrupt sources, this would even be required when using a true interrupt routine, since as soon as TWINT is re-asserted, the next bus transaction will start.

Note [9]

Since the TWI bus is multi-master capable, there is potential for a bus contention when one master starts to access the bus. Normally, the TWI 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.

Note [10]

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 (SLA), but this time with read intent (R/~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.

Note [11]

If the EEPROM 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 SDA after transfering the SLA+R/W packet as a NACK to its selection request. Thus, the select process is simply started over (effectively causing a 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 MAX_ITER.

Note [12]

This is called master receiver mode: the bus master still supplies the SCL clock, but the device slave drives the SDA line with the appropriate data. After 8 data bits, the master responds with an ACK bit (SDA driven low) in order to request another data transfer from the slave, or it can leave the SDA line high (NACK), indicating to the slave that it is going to stop the transfer now. Assertion of ACK is handled by setting the TWEA bit in TWCR when starting the current transfer.

Note [13]

The control word sent out in order to initiate the transfer of the next data packet is initially set up to assert the TWEA bit. During the last loop iteration, TWEA is de-asserted so the client will get informed that no further transfer is desired.

Note [14]

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

Note [15]

Writing to the EEPROM device is simpler than reading, since only a master transmitter mode transfer is needed. Note that the first packet after the SLA+W selection is always considered to be the EEPROM 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.

Note [16]

24Cxx devices can become write-protected by strapping their ~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 NACKed by the device. Note that some devices might not implement this.

Automatically generated by Doxygen 1.4.1 on 13 Oct 2005.