Tuesday, March 24, 2009

Simple TWI / I2C communication with AVR ATMega8 and TC1321 DAC

I wanted to set up and test the D/A-converter TC1321 with a AVR, but had no previous knowledge of TWI. These are my experiences:

To make things easier I used a AVR with built in TWI function. I got a little confused on this subject when I read on AVR Freaks that for example the ATTiny26 had TWI function. Actually the microprosessors with a lowercase "y" in the comparison chart has USI which can be used for TWI. The uppercase "Y" for TWI indicates that the uC has built in TWI functionality. With such uCs you can include the to get some free predefined twi-codes.

To connect to a TWI device you need to connect the SCL and SDA lines to the uC. For ATMega8 it is PC4 (SDA) and PC5 (SCL). You then need to connect each of these via a pullup resistor to the source voltage (5V). For this connection I used two 220 ohm resistors.



So to sum up: I found it easier than I thought to interface the TC1321. Reading through descriptions that others have made describing both reading and writing to a slave (EEPROM etc) was not necessary when the only thing I wanted was to send data.

I found it easier than I had thought to communicate with the TC1321. First you need to set up the SCL-clock rate. You can calculate the TWBR with this formula:
TWBR=(fCPU/fSCL-16)/(2*4^TWPS)

So if you run your uC at fCPU=8MHz and you want fSCL=100kHz and try to use a prescaler TWPS=0 you get TWBR=(8e6/100e3-16)/(2*4^0)=32. So you start by setting:

TWPS=0;
TWBR=32;
To send data to the TC1321 you can use two protocols: 1-byte format (8-bits) and 2-byte format (10-bits). The progress of sending data is made in a sequence like this:

1-byte format:
START
SLA+W
COMMAND
DATA
STOP

2-byte format:
START
SLA+W
COMMAND
DATA
DATA
STOP

In between every sending you check the status codes by looking at TW_STATUS. The SLA+W is actually only the slave adress, 0x90.

Here are some functions that can be used to send data to the TC1321:


So to sum up: I found it easier than I thought to interface the TC1321. Reading through descriptions that others have made describing both reading and writing to a slave (EEPROM etc) was not necessary when the only thing I wanted was to send data.