D:/DRISSI/arduino-0022/arduino-0022/libraries/Wire/utility/twi.c
00001 /*
00002   twi.c - TWI/I2C library for Wiring & Arduino
00003   Copyright (c) 2006 Nicholas Zambetti.  All right reserved.
00004 
00005   This library is free software; you can redistribute it and/or
00006   modify it under the terms of the GNU Lesser General Public
00007   License as published by the Free Software Foundation; either
00008   version 2.1 of the License, or (at your option) any later version.
00009 
00010   This library is distributed in the hope that it will be useful,
00011   but WITHOUT ANY WARRANTY; without even the implied warranty of
00012   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00013   Lesser General Public License for more details.
00014 
00015   You should have received a copy of the GNU Lesser General Public
00016   License along with this library; if not, write to the Free Software
00017   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
00018 */
00019 
00020 #include <math.h>
00021 #include <stdlib.h>
00022 #include <inttypes.h>
00023 #include <avr/io.h>
00024 #include <avr/interrupt.h>
00025 #include <compat/twi.h>
00026 
00027 #ifndef cbi
00028 #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
00029 #endif
00030 
00031 #ifndef sbi
00032 #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
00033 #endif
00034 
00035 #include "twi.h"
00036 
00037 static volatile uint8_t twi_state;
00038 static uint8_t twi_slarw;
00039 
00040 static void (*twi_onSlaveTransmit)(void);
00041 static void (*twi_onSlaveReceive)(uint8_t*, int);
00042 
00043 static uint8_t twi_masterBuffer[TWI_BUFFER_LENGTH];
00044 static volatile uint8_t twi_masterBufferIndex;
00045 static uint8_t twi_masterBufferLength;
00046 
00047 static uint8_t twi_txBuffer[TWI_BUFFER_LENGTH];
00048 static volatile uint8_t twi_txBufferIndex;
00049 static volatile uint8_t twi_txBufferLength;
00050 
00051 static uint8_t twi_rxBuffer[TWI_BUFFER_LENGTH];
00052 static volatile uint8_t twi_rxBufferIndex;
00053 
00054 static volatile uint8_t twi_error;
00055 
00056 /* 
00057  * Function twi_init
00058  * Desc     readys twi pins and sets twi bitrate
00059  * Input    none
00060  * Output   none
00061  */
00062 void twi_init(void)
00063 {
00064   // initialize state
00065   twi_state = TWI_READY;
00066 
00067   #if defined(__AVR_ATmega168__) || defined(__AVR_ATmega8__) || defined(__AVR_ATmega328P__)
00068     // activate internal pull-ups for twi
00069     // as per note from atmega8 manual pg167
00070     sbi(PORTC, 4);
00071     sbi(PORTC, 5);
00072   #else
00073     // activate internal pull-ups for twi
00074     // as per note from atmega128 manual pg204
00075     sbi(PORTD, 0);
00076     sbi(PORTD, 1);
00077   #endif
00078 
00079   // initialize twi prescaler and bit rate
00080   cbi(TWSR, TWPS0);
00081   cbi(TWSR, TWPS1);
00082   TWBR = ((CPU_FREQ / TWI_FREQ) - 16) / 2;
00083 
00084   /* twi bit rate formula from atmega128 manual pg 204
00085   SCL Frequency = CPU Clock Frequency / (16 + (2 * TWBR))
00086   note: TWBR should be 10 or higher for master mode
00087   It is 72 for a 16mhz Wiring board with 100kHz TWI */
00088 
00089   // enable twi module, acks, and twi interrupt
00090   TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA);
00091 }
00092 
00093 /* 
00094  * Function twi_slaveInit
00095  * Desc     sets slave address and enables interrupt
00096  * Input    none
00097  * Output   none
00098  */
00099 void twi_setAddress(uint8_t address)
00100 {
00101   // set twi slave address (skip over TWGCE bit)
00102   TWAR = address << 1;
00103 }
00104 
00105 /* 
00106  * Function twi_readFrom
00107  * Desc     attempts to become twi bus master and read a
00108  *          series of bytes from a device on the bus
00109  * Input    address: 7bit i2c device address
00110  *          data: pointer to byte array
00111  *          length: number of bytes to read into array
00112  * Output   number of bytes read
00113  */
00114 uint8_t twi_readFrom(uint8_t address, uint8_t* data, uint8_t length)
00115 {
00116   uint8_t i;
00117 
00118   // ensure data will fit into buffer
00119   if(TWI_BUFFER_LENGTH < length){
00120     return 0;
00121   }
00122 
00123   // wait until twi is ready, become master receiver
00124   while(TWI_READY != twi_state){
00125     continue;
00126   }
00127   twi_state = TWI_MRX;
00128   // reset error state (0xFF.. no error occured)
00129   twi_error = 0xFF;
00130 
00131   // initialize buffer iteration vars
00132   twi_masterBufferIndex = 0;
00133   twi_masterBufferLength = length-1;  // This is not intuitive, read on...
00134   // On receive, the previously configured ACK/NACK setting is transmitted in
00135   // response to the received byte before the interrupt is signalled. 
00136   // Therefor we must actually set NACK when the _next_ to last byte is
00137   // received, causing that NACK to be sent in response to receiving the last
00138   // expected byte of data.
00139 
00140   // build sla+w, slave device address + w bit
00141   twi_slarw = TW_READ;
00142   twi_slarw |= address << 1;
00143 
00144   // send start condition
00145   TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTA);
00146 
00147   // wait for read operation to complete
00148   while(TWI_MRX == twi_state){
00149     continue;
00150   }
00151 
00152   if (twi_masterBufferIndex < length)
00153     length = twi_masterBufferIndex;
00154 
00155   // copy twi buffer to data
00156   for(i = 0; i < length; ++i){
00157     data[i] = twi_masterBuffer[i];
00158   }
00159         
00160   return length;
00161 }
00162 
00163 /* 
00164  * Function twi_writeTo
00165  * Desc     attempts to become twi bus master and write a
00166  *          series of bytes to a device on the bus
00167  * Input    address: 7bit i2c device address
00168  *          data: pointer to byte array
00169  *          length: number of bytes in array
00170  *          wait: boolean indicating to wait for write or not
00171  * Output   0 .. success
00172  *          1 .. length to long for buffer
00173  *          2 .. address send, NACK received
00174  *          3 .. data send, NACK received
00175  *          4 .. other twi error (lost bus arbitration, bus error, ..)
00176  */
00177 uint8_t twi_writeTo(uint8_t address, uint8_t* data, uint8_t length, uint8_t wait)
00178 {
00179   uint8_t i;
00180 
00181   // ensure data will fit into buffer
00182   if(TWI_BUFFER_LENGTH < length){
00183     return 1;
00184   }
00185 
00186   // wait until twi is ready, become master transmitter
00187   while(TWI_READY != twi_state){
00188     continue;
00189   }
00190   twi_state = TWI_MTX;
00191   // reset error state (0xFF.. no error occured)
00192   twi_error = 0xFF;
00193 
00194   // initialize buffer iteration vars
00195   twi_masterBufferIndex = 0;
00196   twi_masterBufferLength = length;
00197   
00198   // copy data to twi buffer
00199   for(i = 0; i < length; ++i){
00200     twi_masterBuffer[i] = data[i];
00201   }
00202   
00203   // build sla+w, slave device address + w bit
00204   twi_slarw = TW_WRITE;
00205   twi_slarw |= address << 1;
00206   
00207   // send start condition
00208   TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTA);
00209 
00210   // wait for write operation to complete
00211   while(wait && (TWI_MTX == twi_state)){
00212     continue;
00213   }
00214   
00215   if (twi_error == 0xFF)
00216     return 0;   // success
00217   else if (twi_error == TW_MT_SLA_NACK)
00218     return 2;   // error: address send, nack received
00219   else if (twi_error == TW_MT_DATA_NACK)
00220     return 3;   // error: data send, nack received
00221   else
00222     return 4;   // other twi error
00223 }
00224 
00225 /* 
00226  * Function twi_transmit
00227  * Desc     fills slave tx buffer with data
00228  *          must be called in slave tx event callback
00229  * Input    data: pointer to byte array
00230  *          length: number of bytes in array
00231  * Output   1 length too long for buffer
00232  *          2 not slave transmitter
00233  *          0 ok
00234  */
00235 uint8_t twi_transmit(uint8_t* data, uint8_t length)
00236 {
00237   uint8_t i;
00238 
00239   // ensure data will fit into buffer
00240   if(TWI_BUFFER_LENGTH < length){
00241     return 1;
00242   }
00243   
00244   // ensure we are currently a slave transmitter
00245   if(TWI_STX != twi_state){
00246     return 2;
00247   }
00248   
00249   // set length and copy data into tx buffer
00250   twi_txBufferLength = length;
00251   for(i = 0; i < length; ++i){
00252     twi_txBuffer[i] = data[i];
00253   }
00254   
00255   return 0;
00256 }
00257 
00258 /* 
00259  * Function twi_attachSlaveRxEvent
00260  * Desc     sets function called before a slave read operation
00261  * Input    function: callback function to use
00262  * Output   none
00263  */
00264 void twi_attachSlaveRxEvent( void (*function)(uint8_t*, int) )
00265 {
00266   twi_onSlaveReceive = function;
00267 }
00268 
00269 /* 
00270  * Function twi_attachSlaveTxEvent
00271  * Desc     sets function called before a slave write operation
00272  * Input    function: callback function to use
00273  * Output   none
00274  */
00275 void twi_attachSlaveTxEvent( void (*function)(void) )
00276 {
00277   twi_onSlaveTransmit = function;
00278 }
00279 
00280 /* 
00281  * Function twi_reply
00282  * Desc     sends byte or readys receive line
00283  * Input    ack: byte indicating to ack or to nack
00284  * Output   none
00285  */
00286 void twi_reply(uint8_t ack)
00287 {
00288   // transmit master read ready signal, with or without ack
00289   if(ack){
00290     TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWINT) | _BV(TWEA);
00291   }else{
00292           TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWINT);
00293   }
00294 }
00295 
00296 /* 
00297  * Function twi_stop
00298  * Desc     relinquishes bus master status
00299  * Input    none
00300  * Output   none
00301  */
00302 void twi_stop(void)
00303 {
00304   // send stop condition
00305   TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTO);
00306 
00307   // wait for stop condition to be exectued on bus
00308   // TWINT is not set after a stop condition!
00309   while(TWCR & _BV(TWSTO)){
00310     continue;
00311   }
00312 
00313   // update twi state
00314   twi_state = TWI_READY;
00315 }
00316 
00317 /* 
00318  * Function twi_releaseBus
00319  * Desc     releases bus control
00320  * Input    none
00321  * Output   none
00322  */
00323 void twi_releaseBus(void)
00324 {
00325   // release bus
00326   TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT);
00327 
00328   // update twi state
00329   twi_state = TWI_READY;
00330 }
00331 
00332 SIGNAL(TWI_vect)
00333 {
00334   switch(TW_STATUS){
00335     // All Master
00336     case TW_START:     // sent start condition
00337     case TW_REP_START: // sent repeated start condition
00338       // copy device address and r/w bit to output register and ack
00339       TWDR = twi_slarw;
00340       twi_reply(1);
00341       break;
00342 
00343     // Master Transmitter
00344     case TW_MT_SLA_ACK:  // slave receiver acked address
00345     case TW_MT_DATA_ACK: // slave receiver acked data
00346       // if there is data to send, send it, otherwise stop 
00347       if(twi_masterBufferIndex < twi_masterBufferLength){
00348         // copy data to output register and ack
00349         TWDR = twi_masterBuffer[twi_masterBufferIndex++];
00350         twi_reply(1);
00351       }else{
00352         twi_stop();
00353       }
00354       break;
00355     case TW_MT_SLA_NACK:  // address sent, nack received
00356       twi_error = TW_MT_SLA_NACK;
00357       twi_stop();
00358       break;
00359     case TW_MT_DATA_NACK: // data sent, nack received
00360       twi_error = TW_MT_DATA_NACK;
00361       twi_stop();
00362       break;
00363     case TW_MT_ARB_LOST: // lost bus arbitration
00364       twi_error = TW_MT_ARB_LOST;
00365       twi_releaseBus();
00366       break;
00367 
00368     // Master Receiver
00369     case TW_MR_DATA_ACK: // data received, ack sent
00370       // put byte into buffer
00371       twi_masterBuffer[twi_masterBufferIndex++] = TWDR;
00372     case TW_MR_SLA_ACK:  // address sent, ack received
00373       // ack if more bytes are expected, otherwise nack
00374       if(twi_masterBufferIndex < twi_masterBufferLength){
00375         twi_reply(1);
00376       }else{
00377         twi_reply(0);
00378       }
00379       break;
00380     case TW_MR_DATA_NACK: // data received, nack sent
00381       // put final byte into buffer
00382       twi_masterBuffer[twi_masterBufferIndex++] = TWDR;
00383     case TW_MR_SLA_NACK: // address sent, nack received
00384       twi_stop();
00385       break;
00386     // TW_MR_ARB_LOST handled by TW_MT_ARB_LOST case
00387 
00388     // Slave Receiver
00389     case TW_SR_SLA_ACK:   // addressed, returned ack
00390     case TW_SR_GCALL_ACK: // addressed generally, returned ack
00391     case TW_SR_ARB_LOST_SLA_ACK:   // lost arbitration, returned ack
00392     case TW_SR_ARB_LOST_GCALL_ACK: // lost arbitration, returned ack
00393       // enter slave receiver mode
00394       twi_state = TWI_SRX;
00395       // indicate that rx buffer can be overwritten and ack
00396       twi_rxBufferIndex = 0;
00397       twi_reply(1);
00398       break;
00399     case TW_SR_DATA_ACK:       // data received, returned ack
00400     case TW_SR_GCALL_DATA_ACK: // data received generally, returned ack
00401       // if there is still room in the rx buffer
00402       if(twi_rxBufferIndex < TWI_BUFFER_LENGTH){
00403         // put byte in buffer and ack
00404         twi_rxBuffer[twi_rxBufferIndex++] = TWDR;
00405         twi_reply(1);
00406       }else{
00407         // otherwise nack
00408         twi_reply(0);
00409       }
00410       break;
00411     case TW_SR_STOP: // stop or repeated start condition received
00412       // put a null char after data if there's room
00413       if(twi_rxBufferIndex < TWI_BUFFER_LENGTH){
00414         twi_rxBuffer[twi_rxBufferIndex] = '\0';
00415       }
00416       // sends ack and stops interface for clock stretching
00417       twi_stop();
00418       // callback to user defined callback
00419       twi_onSlaveReceive(twi_rxBuffer, twi_rxBufferIndex);
00420       // since we submit rx buffer to "wire" library, we can reset it
00421       twi_rxBufferIndex = 0;
00422       // ack future responses and leave slave receiver state
00423       twi_releaseBus();
00424       break;
00425     case TW_SR_DATA_NACK:       // data received, returned nack
00426     case TW_SR_GCALL_DATA_NACK: // data received generally, returned nack
00427       // nack back at master
00428       twi_reply(0);
00429       break;
00430     
00431     // Slave Transmitter
00432     case TW_ST_SLA_ACK:          // addressed, returned ack
00433     case TW_ST_ARB_LOST_SLA_ACK: // arbitration lost, returned ack
00434       // enter slave transmitter mode
00435       twi_state = TWI_STX;
00436       // ready the tx buffer index for iteration
00437       twi_txBufferIndex = 0;
00438       // set tx buffer length to be zero, to verify if user changes it
00439       twi_txBufferLength = 0;
00440       // request for txBuffer to be filled and length to be set
00441       // note: user must call twi_transmit(bytes, length) to do this
00442       twi_onSlaveTransmit();
00443       // if they didn't change buffer & length, initialize it
00444       if(0 == twi_txBufferLength){
00445         twi_txBufferLength = 1;
00446         twi_txBuffer[0] = 0x00;
00447       }
00448       // transmit first byte from buffer, fall
00449     case TW_ST_DATA_ACK: // byte sent, ack returned
00450       // copy data to output register
00451       TWDR = twi_txBuffer[twi_txBufferIndex++];
00452       // if there is more to send, ack, otherwise nack
00453       if(twi_txBufferIndex < twi_txBufferLength){
00454         twi_reply(1);
00455       }else{
00456         twi_reply(0);
00457       }
00458       break;
00459     case TW_ST_DATA_NACK: // received nack, we are done 
00460     case TW_ST_LAST_DATA: // received ack, but we are done already!
00461       // ack future responses
00462       twi_reply(1);
00463       // leave slave receiver state
00464       twi_state = TWI_READY;
00465       break;
00466 
00467     // All
00468     case TW_NO_INFO:   // no state information
00469       break;
00470     case TW_BUS_ERROR: // bus error, illegal stop/start
00471       twi_error = TW_BUS_ERROR;
00472       twi_stop();
00473       break;
00474   }
00475 }
00476