• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1  /*
2    twi.c - TWI/I2C library for Wiring & Arduino
3    Copyright (c) 2006 Nicholas Zambetti.  All right reserved.
4  
5    This library is free software; you can redistribute it and/or
6    modify it under the terms of the GNU Lesser General Public
7    License as published by the Free Software Foundation; either
8    version 2.1 of the License, or (at your option) any later version.
9  
10    This library is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    Lesser General Public License for more details.
14  
15    You should have received a copy of the GNU Lesser General Public
16    License along with this library; if not, write to the Free Software
17    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
18  */
19  
20  #include <math.h>
21  #include <stdlib.h>
22  #include <inttypes.h>
23  #include <avr/io.h>
24  #include <avr/interrupt.h>
25  #include <compat/twi.h>
26  
27  #ifndef cbi
28  #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
29  #endif
30  
31  #ifndef sbi
32  #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
33  #endif
34  
35  #include "twi.h"
36  
37  static volatile uint8_t twi_state;
38  static uint8_t twi_slarw;
39  
40  static void (*twi_onSlaveTransmit)(void);
41  static void (*twi_onSlaveReceive)(uint8_t*, int);
42  
43  static uint8_t twi_masterBuffer[TWI_BUFFER_LENGTH];
44  static volatile uint8_t twi_masterBufferIndex;
45  static uint8_t twi_masterBufferLength;
46  
47  static uint8_t twi_txBuffer[TWI_BUFFER_LENGTH];
48  static volatile uint8_t twi_txBufferIndex;
49  static volatile uint8_t twi_txBufferLength;
50  
51  static uint8_t twi_rxBuffer[TWI_BUFFER_LENGTH];
52  static volatile uint8_t twi_rxBufferIndex;
53  
54  static volatile uint8_t twi_error;
55  
56  /*
57   * Function twi_init
58   * Desc     readys twi pins and sets twi bitrate
59   * Input    none
60   * Output   none
61   */
twi_init(void)62  void twi_init(void)
63  {
64    // initialize state
65    twi_state = TWI_READY;
66  
67    #if defined(__AVR_ATmega168__) || defined(__AVR_ATmega8__) || defined(__AVR_ATmega328P__)
68      // activate internal pull-ups for twi
69      // as per note from atmega8 manual pg167
70      sbi(PORTC, 4);
71      sbi(PORTC, 5);
72    #else
73      // activate internal pull-ups for twi
74      // as per note from atmega128 manual pg204
75      sbi(PORTD, 0);
76      sbi(PORTD, 1);
77    #endif
78  
79    // initialize twi prescaler and bit rate
80    cbi(TWSR, TWPS0);
81    cbi(TWSR, TWPS1);
82    TWBR = ((CPU_FREQ / TWI_FREQ) - 16) / 2;
83  
84    /* twi bit rate formula from atmega128 manual pg 204
85    SCL Frequency = CPU Clock Frequency / (16 + (2 * TWBR))
86    note: TWBR should be 10 or higher for master mode
87    It is 72 for a 16mhz Wiring board with 100kHz TWI */
88  
89    // enable twi module, acks, and twi interrupt
90    TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA);
91  }
92  
93  /*
94   * Function twi_slaveInit
95   * Desc     sets slave address and enables interrupt
96   * Input    none
97   * Output   none
98   */
twi_setAddress(uint8_t address)99  void twi_setAddress(uint8_t address)
100  {
101    // set twi slave address (skip over TWGCE bit)
102    TWAR = address << 1;
103  }
104  
105  /*
106   * Function twi_readFrom
107   * Desc     attempts to become twi bus master and read a
108   *          series of bytes from a device on the bus
109   * Input    address: 7bit i2c device address
110   *          data: pointer to byte array
111   *          length: number of bytes to read into array
112   * Output   number of bytes read
113   */
twi_readFrom(uint8_t address,uint8_t * data,uint8_t length)114  uint8_t twi_readFrom(uint8_t address, uint8_t* data, uint8_t length)
115  {
116    uint8_t i;
117  
118    // ensure data will fit into buffer
119    if(TWI_BUFFER_LENGTH < length){
120      return 0;
121    }
122  
123    // wait until twi is ready, become master receiver
124    while(TWI_READY != twi_state){
125      continue;
126    }
127    twi_state = TWI_MRX;
128    // reset error state (0xFF.. no error occured)
129    twi_error = 0xFF;
130  
131    // initialize buffer iteration vars
132    twi_masterBufferIndex = 0;
133    twi_masterBufferLength = length-1;  // This is not intuitive, read on...
134    // On receive, the previously configured ACK/NACK setting is transmitted in
135    // response to the received byte before the interrupt is signalled.
136    // Therefor we must actually set NACK when the _next_ to last byte is
137    // received, causing that NACK to be sent in response to receiving the last
138    // expected byte of data.
139  
140    // build sla+w, slave device address + w bit
141    twi_slarw = TW_READ;
142    twi_slarw |= address << 1;
143  
144    // send start condition
145    TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTA);
146  
147    // wait for read operation to complete
148    while(TWI_MRX == twi_state){
149      continue;
150    }
151  
152    if (twi_masterBufferIndex < length)
153      length = twi_masterBufferIndex;
154  
155    // copy twi buffer to data
156    for(i = 0; i < length; ++i){
157      data[i] = twi_masterBuffer[i];
158    }
159  
160    return length;
161  }
162  
163  /*
164   * Function twi_writeTo
165   * Desc     attempts to become twi bus master and write a
166   *          series of bytes to a device on the bus
167   * Input    address: 7bit i2c device address
168   *          data: pointer to byte array
169   *          length: number of bytes in array
170   *          wait: boolean indicating to wait for write or not
171   * Output   0 .. success
172   *          1 .. length to long for buffer
173   *          2 .. address send, NACK received
174   *          3 .. data send, NACK received
175   *          4 .. other twi error (lost bus arbitration, bus error, ..)
176   */
twi_writeTo(uint8_t address,uint8_t * data,uint8_t length,uint8_t wait)177  uint8_t twi_writeTo(uint8_t address, uint8_t* data, uint8_t length, uint8_t wait)
178  {
179    uint8_t i;
180  
181    // ensure data will fit into buffer
182    if(TWI_BUFFER_LENGTH < length){
183      return 1;
184    }
185  
186    // wait until twi is ready, become master transmitter
187    while(TWI_READY != twi_state){
188      continue;
189    }
190    twi_state = TWI_MTX;
191    // reset error state (0xFF.. no error occured)
192    twi_error = 0xFF;
193  
194    // initialize buffer iteration vars
195    twi_masterBufferIndex = 0;
196    twi_masterBufferLength = length;
197  
198    // copy data to twi buffer
199    for(i = 0; i < length; ++i){
200      twi_masterBuffer[i] = data[i];
201    }
202  
203    // build sla+w, slave device address + w bit
204    twi_slarw = TW_WRITE;
205    twi_slarw |= address << 1;
206  
207    // send start condition
208    TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTA);
209  
210    // wait for write operation to complete
211    while(wait && (TWI_MTX == twi_state)){
212      continue;
213    }
214  
215    if (twi_error == 0xFF)
216      return 0;	// success
217    else if (twi_error == TW_MT_SLA_NACK)
218      return 2;	// error: address send, nack received
219    else if (twi_error == TW_MT_DATA_NACK)
220      return 3;	// error: data send, nack received
221    else
222      return 4;	// other twi error
223  }
224  
225  /*
226   * Function twi_transmit
227   * Desc     fills slave tx buffer with data
228   *          must be called in slave tx event callback
229   * Input    data: pointer to byte array
230   *          length: number of bytes in array
231   * Output   1 length too long for buffer
232   *          2 not slave transmitter
233   *          0 ok
234   */
twi_transmit(uint8_t * data,uint8_t length)235  uint8_t twi_transmit(uint8_t* data, uint8_t length)
236  {
237    uint8_t i;
238  
239    // ensure data will fit into buffer
240    if(TWI_BUFFER_LENGTH < length){
241      return 1;
242    }
243  
244    // ensure we are currently a slave transmitter
245    if(TWI_STX != twi_state){
246      return 2;
247    }
248  
249    // set length and copy data into tx buffer
250    twi_txBufferLength = length;
251    for(i = 0; i < length; ++i){
252      twi_txBuffer[i] = data[i];
253    }
254  
255    return 0;
256  }
257  
258  /*
259   * Function twi_attachSlaveRxEvent
260   * Desc     sets function called before a slave read operation
261   * Input    function: callback function to use
262   * Output   none
263   */
twi_attachSlaveRxEvent(void (* function)(uint8_t *,int))264  void twi_attachSlaveRxEvent( void (*function)(uint8_t*, int) )
265  {
266    twi_onSlaveReceive = function;
267  }
268  
269  /*
270   * Function twi_attachSlaveTxEvent
271   * Desc     sets function called before a slave write operation
272   * Input    function: callback function to use
273   * Output   none
274   */
twi_attachSlaveTxEvent(void (* function)(void))275  void twi_attachSlaveTxEvent( void (*function)(void) )
276  {
277    twi_onSlaveTransmit = function;
278  }
279  
280  /*
281   * Function twi_reply
282   * Desc     sends byte or readys receive line
283   * Input    ack: byte indicating to ack or to nack
284   * Output   none
285   */
twi_reply(uint8_t ack)286  void twi_reply(uint8_t ack)
287  {
288    // transmit master read ready signal, with or without ack
289    if(ack){
290      TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWINT) | _BV(TWEA);
291    }else{
292  	  TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWINT);
293    }
294  }
295  
296  /*
297   * Function twi_stop
298   * Desc     relinquishes bus master status
299   * Input    none
300   * Output   none
301   */
twi_stop(void)302  void twi_stop(void)
303  {
304    // send stop condition
305    TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTO);
306  
307    // wait for stop condition to be exectued on bus
308    // TWINT is not set after a stop condition!
309    while(TWCR & _BV(TWSTO)){
310      continue;
311    }
312  
313    // update twi state
314    twi_state = TWI_READY;
315  }
316  
317  /*
318   * Function twi_releaseBus
319   * Desc     releases bus control
320   * Input    none
321   * Output   none
322   */
twi_releaseBus(void)323  void twi_releaseBus(void)
324  {
325    // release bus
326    TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT);
327  
328    // update twi state
329    twi_state = TWI_READY;
330  }
331  
SIGNAL(TWI_vect)332  SIGNAL(TWI_vect)
333  {
334    switch(TW_STATUS){
335      // All Master
336      case TW_START:     // sent start condition
337      case TW_REP_START: // sent repeated start condition
338        // copy device address and r/w bit to output register and ack
339        TWDR = twi_slarw;
340        twi_reply(1);
341        break;
342  
343      // Master Transmitter
344      case TW_MT_SLA_ACK:  // slave receiver acked address
345      case TW_MT_DATA_ACK: // slave receiver acked data
346        // if there is data to send, send it, otherwise stop
347        if(twi_masterBufferIndex < twi_masterBufferLength){
348          // copy data to output register and ack
349          TWDR = twi_masterBuffer[twi_masterBufferIndex++];
350          twi_reply(1);
351        }else{
352          twi_stop();
353        }
354        break;
355      case TW_MT_SLA_NACK:  // address sent, nack received
356        twi_error = TW_MT_SLA_NACK;
357        twi_stop();
358        break;
359      case TW_MT_DATA_NACK: // data sent, nack received
360        twi_error = TW_MT_DATA_NACK;
361        twi_stop();
362        break;
363      case TW_MT_ARB_LOST: // lost bus arbitration
364        twi_error = TW_MT_ARB_LOST;
365        twi_releaseBus();
366        break;
367  
368      // Master Receiver
369      case TW_MR_DATA_ACK: // data received, ack sent
370        // put byte into buffer
371        twi_masterBuffer[twi_masterBufferIndex++] = TWDR;
372      case TW_MR_SLA_ACK:  // address sent, ack received
373        // ack if more bytes are expected, otherwise nack
374        if(twi_masterBufferIndex < twi_masterBufferLength){
375          twi_reply(1);
376        }else{
377          twi_reply(0);
378        }
379        break;
380      case TW_MR_DATA_NACK: // data received, nack sent
381        // put final byte into buffer
382        twi_masterBuffer[twi_masterBufferIndex++] = TWDR;
383      case TW_MR_SLA_NACK: // address sent, nack received
384        twi_stop();
385        break;
386      // TW_MR_ARB_LOST handled by TW_MT_ARB_LOST case
387  
388      // Slave Receiver
389      case TW_SR_SLA_ACK:   // addressed, returned ack
390      case TW_SR_GCALL_ACK: // addressed generally, returned ack
391      case TW_SR_ARB_LOST_SLA_ACK:   // lost arbitration, returned ack
392      case TW_SR_ARB_LOST_GCALL_ACK: // lost arbitration, returned ack
393        // enter slave receiver mode
394        twi_state = TWI_SRX;
395        // indicate that rx buffer can be overwritten and ack
396        twi_rxBufferIndex = 0;
397        twi_reply(1);
398        break;
399      case TW_SR_DATA_ACK:       // data received, returned ack
400      case TW_SR_GCALL_DATA_ACK: // data received generally, returned ack
401        // if there is still room in the rx buffer
402        if(twi_rxBufferIndex < TWI_BUFFER_LENGTH){
403          // put byte in buffer and ack
404          twi_rxBuffer[twi_rxBufferIndex++] = TWDR;
405          twi_reply(1);
406        }else{
407          // otherwise nack
408          twi_reply(0);
409        }
410        break;
411      case TW_SR_STOP: // stop or repeated start condition received
412        // put a null char after data if there's room
413        if(twi_rxBufferIndex < TWI_BUFFER_LENGTH){
414          twi_rxBuffer[twi_rxBufferIndex] = '\0';
415        }
416        // sends ack and stops interface for clock stretching
417        twi_stop();
418        // callback to user defined callback
419        twi_onSlaveReceive(twi_rxBuffer, twi_rxBufferIndex);
420        // since we submit rx buffer to "wire" library, we can reset it
421        twi_rxBufferIndex = 0;
422        // ack future responses and leave slave receiver state
423        twi_releaseBus();
424        break;
425      case TW_SR_DATA_NACK:       // data received, returned nack
426      case TW_SR_GCALL_DATA_NACK: // data received generally, returned nack
427        // nack back at master
428        twi_reply(0);
429        break;
430  
431      // Slave Transmitter
432      case TW_ST_SLA_ACK:          // addressed, returned ack
433      case TW_ST_ARB_LOST_SLA_ACK: // arbitration lost, returned ack
434        // enter slave transmitter mode
435        twi_state = TWI_STX;
436        // ready the tx buffer index for iteration
437        twi_txBufferIndex = 0;
438        // set tx buffer length to be zero, to verify if user changes it
439        twi_txBufferLength = 0;
440        // request for txBuffer to be filled and length to be set
441        // note: user must call twi_transmit(bytes, length) to do this
442        twi_onSlaveTransmit();
443        // if they didn't change buffer & length, initialize it
444        if(0 == twi_txBufferLength){
445          twi_txBufferLength = 1;
446          twi_txBuffer[0] = 0x00;
447        }
448        // transmit first byte from buffer, fall
449      case TW_ST_DATA_ACK: // byte sent, ack returned
450        // copy data to output register
451        TWDR = twi_txBuffer[twi_txBufferIndex++];
452        // if there is more to send, ack, otherwise nack
453        if(twi_txBufferIndex < twi_txBufferLength){
454          twi_reply(1);
455        }else{
456          twi_reply(0);
457        }
458        break;
459      case TW_ST_DATA_NACK: // received nack, we are done
460      case TW_ST_LAST_DATA: // received ack, but we are done already!
461        // ack future responses
462        twi_reply(1);
463        // leave slave receiver state
464        twi_state = TWI_READY;
465        break;
466  
467      // All
468      case TW_NO_INFO:   // no state information
469        break;
470      case TW_BUS_ERROR: // bus error, illegal stop/start
471        twi_error = TW_BUS_ERROR;
472        twi_stop();
473        break;
474    }
475  }
476  
477