Statistics
| Branch: | Revision:

root / arduino-1.0 / libraries / Wire / utility / twi.c @ 58d82c77

History | View | Annotate | Download (13.1 KB)

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
#include "Arduino.h" // for digitalWrite
27

    
28
#ifndef cbi
29
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
30
#endif
31

    
32
#ifndef sbi
33
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
34
#endif
35

    
36
#include "pins_arduino.h"
37
#include "twi.h"
38

    
39
static volatile uint8_t twi_state;
40
static uint8_t twi_slarw;
41

    
42
static void (*twi_onSlaveTransmit)(void);
43
static void (*twi_onSlaveReceive)(uint8_t*, int);
44

    
45
static uint8_t twi_masterBuffer[TWI_BUFFER_LENGTH];
46
static volatile uint8_t twi_masterBufferIndex;
47
static uint8_t twi_masterBufferLength;
48

    
49
static uint8_t twi_txBuffer[TWI_BUFFER_LENGTH];
50
static volatile uint8_t twi_txBufferIndex;
51
static volatile uint8_t twi_txBufferLength;
52

    
53
static uint8_t twi_rxBuffer[TWI_BUFFER_LENGTH];
54
static volatile uint8_t twi_rxBufferIndex;
55

    
56
static volatile uint8_t twi_error;
57

    
58
/* 
59
 * Function twi_init
60
 * Desc     readys twi pins and sets twi bitrate
61
 * Input    none
62
 * Output   none
63
 */
64
void twi_init(void)
65
{
66
  // initialize state
67
  twi_state = TWI_READY;
68
  
69
  // activate internal pullups for twi.
70
  digitalWrite(SDA, 1);
71
  digitalWrite(SCL, 1);
72

    
73
  // initialize twi prescaler and bit rate
74
  cbi(TWSR, TWPS0);
75
  cbi(TWSR, TWPS1);
76
  TWBR = ((F_CPU / TWI_FREQ) - 16) / 2;
77

    
78
  /* twi bit rate formula from atmega128 manual pg 204
79
  SCL Frequency = CPU Clock Frequency / (16 + (2 * TWBR))
80
  note: TWBR should be 10 or higher for master mode
81
  It is 72 for a 16mhz Wiring board with 100kHz TWI */
82

    
83
  // enable twi module, acks, and twi interrupt
84
  TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA);
85
}
86

    
87
/* 
88
 * Function twi_slaveInit
89
 * Desc     sets slave address and enables interrupt
90
 * Input    none
91
 * Output   none
92
 */
93
void twi_setAddress(uint8_t address)
94
{
95
  // set twi slave address (skip over TWGCE bit)
96
  TWAR = address << 1;
97
}
98

    
99
/* 
100
 * Function twi_readFrom
101
 * Desc     attempts to become twi bus master and read a
102
 *          series of bytes from a device on the bus
103
 * Input    address: 7bit i2c device address
104
 *          data: pointer to byte array
105
 *          length: number of bytes to read into array
106
 * Output   number of bytes read
107
 */
108
uint8_t twi_readFrom(uint8_t address, uint8_t* data, uint8_t length)
109
{
110
  uint8_t i;
111

    
112
  // ensure data will fit into buffer
113
  if(TWI_BUFFER_LENGTH < length){
114
    return 0;
115
  }
116

    
117
  // wait until twi is ready, become master receiver
118
  while(TWI_READY != twi_state){
119
    continue;
120
  }
121
  twi_state = TWI_MRX;
122
  // reset error state (0xFF.. no error occured)
123
  twi_error = 0xFF;
124

    
125
  // initialize buffer iteration vars
126
  twi_masterBufferIndex = 0;
127
  twi_masterBufferLength = length-1;  // This is not intuitive, read on...
128
  // On receive, the previously configured ACK/NACK setting is transmitted in
129
  // response to the received byte before the interrupt is signalled. 
130
  // Therefor we must actually set NACK when the _next_ to last byte is
131
  // received, causing that NACK to be sent in response to receiving the last
132
  // expected byte of data.
133

    
134
  // build sla+w, slave device address + w bit
135
  twi_slarw = TW_READ;
136
  twi_slarw |= address << 1;
137

    
138
  // send start condition
139
  TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTA);
140

    
141
  // wait for read operation to complete
142
  while(TWI_MRX == twi_state){
143
    continue;
144
  }
145

    
146
  if (twi_masterBufferIndex < length)
147
    length = twi_masterBufferIndex;
148

    
149
  // copy twi buffer to data
150
  for(i = 0; i < length; ++i){
151
    data[i] = twi_masterBuffer[i];
152
  }
153
        
154
  return length;
155
}
156

    
157
/* 
158
 * Function twi_writeTo
159
 * Desc     attempts to become twi bus master and write a
160
 *          series of bytes to a device on the bus
161
 * Input    address: 7bit i2c device address
162
 *          data: pointer to byte array
163
 *          length: number of bytes in array
164
 *          wait: boolean indicating to wait for write or not
165
 * Output   0 .. success
166
 *          1 .. length to long for buffer
167
 *          2 .. address send, NACK received
168
 *          3 .. data send, NACK received
169
 *          4 .. other twi error (lost bus arbitration, bus error, ..)
170
 */
171
uint8_t twi_writeTo(uint8_t address, uint8_t* data, uint8_t length, uint8_t wait)
172
{
173
  uint8_t i;
174

    
175
  // ensure data will fit into buffer
176
  if(TWI_BUFFER_LENGTH < length){
177
    return 1;
178
  }
179

    
180
  // wait until twi is ready, become master transmitter
181
  while(TWI_READY != twi_state){
182
    continue;
183
  }
184
  twi_state = TWI_MTX;
185
  // reset error state (0xFF.. no error occured)
186
  twi_error = 0xFF;
187

    
188
  // initialize buffer iteration vars
189
  twi_masterBufferIndex = 0;
190
  twi_masterBufferLength = length;
191
  
192
  // copy data to twi buffer
193
  for(i = 0; i < length; ++i){
194
    twi_masterBuffer[i] = data[i];
195
  }
196
  
197
  // build sla+w, slave device address + w bit
198
  twi_slarw = TW_WRITE;
199
  twi_slarw |= address << 1;
200
  
201
  // send start condition
202
  TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTA);
203

    
204
  // wait for write operation to complete
205
  while(wait && (TWI_MTX == twi_state)){
206
    continue;
207
  }
208
  
209
  if (twi_error == 0xFF)
210
    return 0;        // success
211
  else if (twi_error == TW_MT_SLA_NACK)
212
    return 2;        // error: address send, nack received
213
  else if (twi_error == TW_MT_DATA_NACK)
214
    return 3;        // error: data send, nack received
215
  else
216
    return 4;        // other twi error
217
}
218

    
219
/* 
220
 * Function twi_transmit
221
 * Desc     fills slave tx buffer with data
222
 *          must be called in slave tx event callback
223
 * Input    data: pointer to byte array
224
 *          length: number of bytes in array
225
 * Output   1 length too long for buffer
226
 *          2 not slave transmitter
227
 *          0 ok
228
 */
229
uint8_t twi_transmit(const uint8_t* data, uint8_t length)
230
{
231
  uint8_t i;
232

    
233
  // ensure data will fit into buffer
234
  if(TWI_BUFFER_LENGTH < length){
235
    return 1;
236
  }
237
  
238
  // ensure we are currently a slave transmitter
239
  if(TWI_STX != twi_state){
240
    return 2;
241
  }
242
  
243
  // set length and copy data into tx buffer
244
  twi_txBufferLength = length;
245
  for(i = 0; i < length; ++i){
246
    twi_txBuffer[i] = data[i];
247
  }
248
  
249
  return 0;
250
}
251

    
252
/* 
253
 * Function twi_attachSlaveRxEvent
254
 * Desc     sets function called before a slave read operation
255
 * Input    function: callback function to use
256
 * Output   none
257
 */
258
void twi_attachSlaveRxEvent( void (*function)(uint8_t*, int) )
259
{
260
  twi_onSlaveReceive = function;
261
}
262

    
263
/* 
264
 * Function twi_attachSlaveTxEvent
265
 * Desc     sets function called before a slave write operation
266
 * Input    function: callback function to use
267
 * Output   none
268
 */
269
void twi_attachSlaveTxEvent( void (*function)(void) )
270
{
271
  twi_onSlaveTransmit = function;
272
}
273

    
274
/* 
275
 * Function twi_reply
276
 * Desc     sends byte or readys receive line
277
 * Input    ack: byte indicating to ack or to nack
278
 * Output   none
279
 */
280
void twi_reply(uint8_t ack)
281
{
282
  // transmit master read ready signal, with or without ack
283
  if(ack){
284
    TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWINT) | _BV(TWEA);
285
  }else{
286
          TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWINT);
287
  }
288
}
289

    
290
/* 
291
 * Function twi_stop
292
 * Desc     relinquishes bus master status
293
 * Input    none
294
 * Output   none
295
 */
296
void twi_stop(void)
297
{
298
  // send stop condition
299
  TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTO);
300

    
301
  // wait for stop condition to be exectued on bus
302
  // TWINT is not set after a stop condition!
303
  while(TWCR & _BV(TWSTO)){
304
    continue;
305
  }
306

    
307
  // update twi state
308
  twi_state = TWI_READY;
309
}
310

    
311
/* 
312
 * Function twi_releaseBus
313
 * Desc     releases bus control
314
 * Input    none
315
 * Output   none
316
 */
317
void twi_releaseBus(void)
318
{
319
  // release bus
320
  TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT);
321

    
322
  // update twi state
323
  twi_state = TWI_READY;
324
}
325

    
326
SIGNAL(TWI_vect)
327
{
328
  switch(TW_STATUS){
329
    // All Master
330
    case TW_START:     // sent start condition
331
    case TW_REP_START: // sent repeated start condition
332
      // copy device address and r/w bit to output register and ack
333
      TWDR = twi_slarw;
334
      twi_reply(1);
335
      break;
336

    
337
    // Master Transmitter
338
    case TW_MT_SLA_ACK:  // slave receiver acked address
339
    case TW_MT_DATA_ACK: // slave receiver acked data
340
      // if there is data to send, send it, otherwise stop 
341
      if(twi_masterBufferIndex < twi_masterBufferLength){
342
        // copy data to output register and ack
343
        TWDR = twi_masterBuffer[twi_masterBufferIndex++];
344
        twi_reply(1);
345
      }else{
346
        twi_stop();
347
      }
348
      break;
349
    case TW_MT_SLA_NACK:  // address sent, nack received
350
      twi_error = TW_MT_SLA_NACK;
351
      twi_stop();
352
      break;
353
    case TW_MT_DATA_NACK: // data sent, nack received
354
      twi_error = TW_MT_DATA_NACK;
355
      twi_stop();
356
      break;
357
    case TW_MT_ARB_LOST: // lost bus arbitration
358
      twi_error = TW_MT_ARB_LOST;
359
      twi_releaseBus();
360
      break;
361

    
362
    // Master Receiver
363
    case TW_MR_DATA_ACK: // data received, ack sent
364
      // put byte into buffer
365
      twi_masterBuffer[twi_masterBufferIndex++] = TWDR;
366
    case TW_MR_SLA_ACK:  // address sent, ack received
367
      // ack if more bytes are expected, otherwise nack
368
      if(twi_masterBufferIndex < twi_masterBufferLength){
369
        twi_reply(1);
370
      }else{
371
        twi_reply(0);
372
      }
373
      break;
374
    case TW_MR_DATA_NACK: // data received, nack sent
375
      // put final byte into buffer
376
      twi_masterBuffer[twi_masterBufferIndex++] = TWDR;
377
    case TW_MR_SLA_NACK: // address sent, nack received
378
      twi_stop();
379
      break;
380
    // TW_MR_ARB_LOST handled by TW_MT_ARB_LOST case
381

    
382
    // Slave Receiver
383
    case TW_SR_SLA_ACK:   // addressed, returned ack
384
    case TW_SR_GCALL_ACK: // addressed generally, returned ack
385
    case TW_SR_ARB_LOST_SLA_ACK:   // lost arbitration, returned ack
386
    case TW_SR_ARB_LOST_GCALL_ACK: // lost arbitration, returned ack
387
      // enter slave receiver mode
388
      twi_state = TWI_SRX;
389
      // indicate that rx buffer can be overwritten and ack
390
      twi_rxBufferIndex = 0;
391
      twi_reply(1);
392
      break;
393
    case TW_SR_DATA_ACK:       // data received, returned ack
394
    case TW_SR_GCALL_DATA_ACK: // data received generally, returned ack
395
      // if there is still room in the rx buffer
396
      if(twi_rxBufferIndex < TWI_BUFFER_LENGTH){
397
        // put byte in buffer and ack
398
        twi_rxBuffer[twi_rxBufferIndex++] = TWDR;
399
        twi_reply(1);
400
      }else{
401
        // otherwise nack
402
        twi_reply(0);
403
      }
404
      break;
405
    case TW_SR_STOP: // stop or repeated start condition received
406
      // put a null char after data if there's room
407
      if(twi_rxBufferIndex < TWI_BUFFER_LENGTH){
408
        twi_rxBuffer[twi_rxBufferIndex] = '\0';
409
      }
410
      // sends ack and stops interface for clock stretching
411
      twi_stop();
412
      // callback to user defined callback
413
      twi_onSlaveReceive(twi_rxBuffer, twi_rxBufferIndex);
414
      // since we submit rx buffer to "wire" library, we can reset it
415
      twi_rxBufferIndex = 0;
416
      // ack future responses and leave slave receiver state
417
      twi_releaseBus();
418
      break;
419
    case TW_SR_DATA_NACK:       // data received, returned nack
420
    case TW_SR_GCALL_DATA_NACK: // data received generally, returned nack
421
      // nack back at master
422
      twi_reply(0);
423
      break;
424
    
425
    // Slave Transmitter
426
    case TW_ST_SLA_ACK:          // addressed, returned ack
427
    case TW_ST_ARB_LOST_SLA_ACK: // arbitration lost, returned ack
428
      // enter slave transmitter mode
429
      twi_state = TWI_STX;
430
      // ready the tx buffer index for iteration
431
      twi_txBufferIndex = 0;
432
      // set tx buffer length to be zero, to verify if user changes it
433
      twi_txBufferLength = 0;
434
      // request for txBuffer to be filled and length to be set
435
      // note: user must call twi_transmit(bytes, length) to do this
436
      twi_onSlaveTransmit();
437
      // if they didn't change buffer & length, initialize it
438
      if(0 == twi_txBufferLength){
439
        twi_txBufferLength = 1;
440
        twi_txBuffer[0] = 0x00;
441
      }
442
      // transmit first byte from buffer, fall
443
    case TW_ST_DATA_ACK: // byte sent, ack returned
444
      // copy data to output register
445
      TWDR = twi_txBuffer[twi_txBufferIndex++];
446
      // if there is more to send, ack, otherwise nack
447
      if(twi_txBufferIndex < twi_txBufferLength){
448
        twi_reply(1);
449
      }else{
450
        twi_reply(0);
451
      }
452
      break;
453
    case TW_ST_DATA_NACK: // received nack, we are done 
454
    case TW_ST_LAST_DATA: // received ack, but we are done already!
455
      // ack future responses
456
      twi_reply(1);
457
      // leave slave receiver state
458
      twi_state = TWI_READY;
459
      break;
460

    
461
    // All
462
    case TW_NO_INFO:   // no state information
463
      break;
464
    case TW_BUS_ERROR: // bus error, illegal stop/start
465
      twi_error = TW_BUS_ERROR;
466
      twi_stop();
467
      break;
468
  }
469
}
470