Subversion Repositories group.electronics

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
117 pfowler 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
  Modified 2012 by Todd Krein (todd@krein.org) to implement repeated starts
20
*/
21
 
22
#include <math.h>
23
#include <stdlib.h>
24
#include <inttypes.h>
25
#include <avr/io.h>
26
#include <avr/interrupt.h>
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 "twi.h"
37
 
38
static volatile uint8_t twi_state;
39
static volatile uint8_t twi_slarw;
40
static volatile uint8_t twi_sendStop;	// should the transaction end with a stop
41
static volatile uint8_t twi_inRepStart;	// in the middle of a repeated start
42
 
43
static void (*twi_onSlaveTransmit)(void);
44
static void (*twi_onSlaveReceive)(uint8_t*, int);
45
 
46
static uint8_t twi_masterBuffer[TWI_BUFFER_LENGTH];
47
static volatile uint8_t twi_masterBufferIndex;
48
static volatile uint8_t twi_masterBufferLength;
49
 
50
static uint8_t twi_txBuffer[TWI_BUFFER_LENGTH];
51
static volatile uint8_t twi_txBufferIndex;
52
static volatile uint8_t twi_txBufferLength;
53
 
54
static uint8_t twi_rxBuffer[TWI_BUFFER_LENGTH];
55
static volatile uint8_t twi_rxBufferIndex;
56
 
57
static volatile uint8_t twi_error;
58
 
59
/* 
60
 * Function twi_init
61
 * Desc     readys twi pins and sets twi bitrate
62
 * Input    none
63
 * Output   none
64
 */
65
void twi_init(void)
66
{
67
  // initialize state
68
  twi_state = TWI_READY;
69
  twi_sendStop = true;		// default value
70
  twi_inRepStart = false;
71
 
72
  // activate internal pullups for twi.
73
  // @TODO: activate pullups
74
  //digitalWrite(SDA, 1);
75
  //digitalWrite(SCL, 1);
76
 
77
  // initialize twi prescaler and bit rate
78
  cbi(TWSR, TWPS0);
79
  cbi(TWSR, TWPS1);
80
  TWBR = ((F_CPU / TWI_FREQ) - 16) / 2;
81
 
82
  /* twi bit rate formula from atmega128 manual pg 204
83
  SCL Frequency = CPU Clock Frequency / (16 + (2 * TWBR))
84
  note: TWBR should be 10 or higher for master mode
85
  It is 72 for a 16mhz Wiring board with 100kHz TWI */
86
 
87
  // enable twi module, acks, and twi interrupt
88
  TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA);
89
}
90
 
91
/* 
92
 * Function twi_slaveInit
93
 * Desc     sets slave address and enables interrupt
94
 * Input    none
95
 * Output   none
96
 */
97
void twi_setAddress(uint8_t address)
98
{
99
  // set twi slave address (skip over TWGCE bit)
100
  TWAR = address << 1;
101
}
102
 
103
/* 
104
 * Function twi_readFrom
105
 * Desc     attempts to become twi bus master and read a
106
 *          series of bytes from a device on the bus
107
 * Input    address: 7bit i2c device address
108
 *          data: pointer to byte array
109
 *          length: number of bytes to read into array
110
 *          sendStop: Boolean indicating whether to send a stop at the end
111
 * Output   number of bytes read
112
 */
113
uint8_t twi_readFrom(uint8_t address, uint8_t* data, uint8_t length, uint8_t sendStop)
114
{
115
  uint8_t i;
116
 
117
  // ensure data will fit into buffer
118
  if(TWI_BUFFER_LENGTH < length){
119
    return 0;
120
  }
121
 
122
  // wait until twi is ready, become master receiver
123
  while(TWI_READY != twi_state){
124
    continue;
125
  }
126
  twi_state = TWI_MRX;
127
  twi_sendStop = sendStop;
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
  if (true == twi_inRepStart) {
145
    // if we're in the repeated start state, then we've already sent the start,
146
    // (@@@ we hope), and the TWI statemachine is just waiting for the address byte.
147
    // We need to remove ourselves from the repeated start state before we enable interrupts,
148
    // since the ISR is ASYNC, and we could get confused if we hit the ISR before cleaning
149
    // up. Also, don't enable the START interrupt. There may be one pending from the 
150
    // repeated start that we sent outselves, and that would really confuse things.
151
    twi_inRepStart = false;			// remember, we're dealing with an ASYNC ISR
152
    TWDR = twi_slarw;
153
    TWCR = _BV(TWINT) | _BV(TWEA) | _BV(TWEN) | _BV(TWIE);	// enable INTs, but not START
154
  }
155
  else
156
    // send start condition
157
    TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTA);
158
 
159
  // wait for read operation to complete
160
  while(TWI_MRX == twi_state){
161
    continue;
162
  }
163
 
164
  if (twi_masterBufferIndex < length)
165
    length = twi_masterBufferIndex;
166
 
167
  // copy twi buffer to data
168
  for(i = 0; i < length; ++i){
169
    data[i] = twi_masterBuffer[i];
170
  }
171
 
172
  return length;
173
}
174
 
175
/* 
176
 * Function twi_writeTo
177
 * Desc     attempts to become twi bus master and write a
178
 *          series of bytes to a device on the bus
179
 * Input    address: 7bit i2c device address
180
 *          data: pointer to byte array
181
 *          length: number of bytes in array
182
 *          wait: boolean indicating to wait for write or not
183
 *          sendStop: boolean indicating whether or not to send a stop at the end
184
 * Output   0 .. success
185
 *          1 .. length to long for buffer
186
 *          2 .. address send, NACK received
187
 *          3 .. data send, NACK received
188
 *          4 .. other twi error (lost bus arbitration, bus error, ..)
189
 */
190
uint8_t twi_writeTo(uint8_t address, uint8_t* data, uint8_t length, uint8_t wait, uint8_t sendStop)
191
{
192
  uint8_t i;
193
 
194
  // ensure data will fit into buffer
195
  if(TWI_BUFFER_LENGTH < length){
196
    return 1;
197
  }
198
 
199
  // wait until twi is ready, become master transmitter
200
  while(TWI_READY != twi_state){
201
    continue;
202
  }
203
  twi_state = TWI_MTX;
204
  twi_sendStop = sendStop;
205
  // reset error state (0xFF.. no error occured)
206
  twi_error = 0xFF;
207
 
208
  // initialize buffer iteration vars
209
  twi_masterBufferIndex = 0;
210
  twi_masterBufferLength = length;
211
 
212
  // copy data to twi buffer
213
  for(i = 0; i < length; ++i){
214
    twi_masterBuffer[i] = data[i];
215
  }
216
 
217
  // build sla+w, slave device address + w bit
218
  twi_slarw = TW_WRITE;
219
  twi_slarw |= address << 1;
220
 
221
  // if we're in a repeated start, then we've already sent the START
222
  // in the ISR. Don't do it again.
223
  //
224
  if (true == twi_inRepStart) {
225
    // if we're in the repeated start state, then we've already sent the start,
226
    // (@@@ we hope), and the TWI statemachine is just waiting for the address byte.
227
    // We need to remove ourselves from the repeated start state before we enable interrupts,
228
    // since the ISR is ASYNC, and we could get confused if we hit the ISR before cleaning
229
    // up. Also, don't enable the START interrupt. There may be one pending from the 
230
    // repeated start that we sent outselves, and that would really confuse things.
231
    twi_inRepStart = false;			// remember, we're dealing with an ASYNC ISR
232
    TWDR = twi_slarw;				
233
    TWCR = _BV(TWINT) | _BV(TWEA) | _BV(TWEN) | _BV(TWIE);	// enable INTs, but not START
234
  }
235
  else
236
    // send start condition
237
    TWCR = _BV(TWINT) | _BV(TWEA) | _BV(TWEN) | _BV(TWIE) | _BV(TWSTA);	// enable INTs
238
 
239
  // wait for write operation to complete
240
  while(wait && (TWI_MTX == twi_state)){
241
    continue;
242
  }
243
 
244
  if (twi_error == 0xFF)
245
    return 0;	// success
246
  else if (twi_error == TW_MT_SLA_NACK)
247
    return 2;	// error: address send, nack received
248
  else if (twi_error == TW_MT_DATA_NACK)
249
    return 3;	// error: data send, nack received
250
  else
251
    return 4;	// other twi error
252
}
253
 
254
/* 
255
 * Function twi_transmit
256
 * Desc     fills slave tx buffer with data
257
 *          must be called in slave tx event callback
258
 * Input    data: pointer to byte array
259
 *          length: number of bytes in array
260
 * Output   1 length too long for buffer
261
 *          2 not slave transmitter
262
 *          0 ok
263
 */
264
uint8_t twi_transmit(const uint8_t* data, uint8_t length)
265
{
266
  uint8_t i;
267
 
268
  // ensure data will fit into buffer
269
  if(TWI_BUFFER_LENGTH < length){
270
    return 1;
271
  }
272
 
273
  // ensure we are currently a slave transmitter
274
  if(TWI_STX != twi_state){
275
    return 2;
276
  }
277
 
278
  // set length and copy data into tx buffer
279
  twi_txBufferLength = length;
280
  for(i = 0; i < length; ++i){
281
    twi_txBuffer[i] = data[i];
282
  }
283
 
284
  return 0;
285
}
286
 
287
/* 
288
 * Function twi_attachSlaveRxEvent
289
 * Desc     sets function called before a slave read operation
290
 * Input    function: callback function to use
291
 * Output   none
292
 */
293
void twi_attachSlaveRxEvent( void (*function)(uint8_t*, int) )
294
{
295
  twi_onSlaveReceive = function;
296
}
297
 
298
/* 
299
 * Function twi_attachSlaveTxEvent
300
 * Desc     sets function called before a slave write operation
301
 * Input    function: callback function to use
302
 * Output   none
303
 */
304
void twi_attachSlaveTxEvent( void (*function)(void) )
305
{
306
  twi_onSlaveTransmit = function;
307
}
308
 
309
/* 
310
 * Function twi_reply
311
 * Desc     sends byte or readys receive line
312
 * Input    ack: byte indicating to ack or to nack
313
 * Output   none
314
 */
315
void twi_reply(uint8_t ack)
316
{
317
  // transmit master read ready signal, with or without ack
318
  if(ack){
319
    TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWINT) | _BV(TWEA);
320
  }else{
321
	  TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWINT);
322
  }
323
}
324
 
325
/* 
326
 * Function twi_stop
327
 * Desc     relinquishes bus master status
328
 * Input    none
329
 * Output   none
330
 */
331
void twi_stop(void)
332
{
333
  // send stop condition
334
  TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTO);
335
 
336
  // wait for stop condition to be exectued on bus
337
  // TWINT is not set after a stop condition!
338
  while(TWCR & _BV(TWSTO)){
339
    continue;
340
  }
341
 
342
  // update twi state
343
  twi_state = TWI_READY;
344
}
345
 
346
/* 
347
 * Function twi_releaseBus
348
 * Desc     releases bus control
349
 * Input    none
350
 * Output   none
351
 */
352
void twi_releaseBus(void)
353
{
354
  // release bus
355
  TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT);
356
 
357
  // update twi state
358
  twi_state = TWI_READY;
359
}
360
 
361
SIGNAL(TWI_vect)
362
{
363
  switch(TW_STATUS){
364
    // All Master
365
    case TW_START:     // sent start condition
366
    case TW_REP_START: // sent repeated start condition
367
      // copy device address and r/w bit to output register and ack
368
      TWDR = twi_slarw;
369
      twi_reply(1);
370
      break;
371
 
372
    // Master Transmitter
373
    case TW_MT_SLA_ACK:  // slave receiver acked address
374
    case TW_MT_DATA_ACK: // slave receiver acked data
375
      // if there is data to send, send it, otherwise stop 
376
      if(twi_masterBufferIndex < twi_masterBufferLength){
377
        // copy data to output register and ack
378
        TWDR = twi_masterBuffer[twi_masterBufferIndex++];
379
        twi_reply(1);
380
      }else{
381
	if (twi_sendStop)
382
          twi_stop();
383
	else {
384
	  twi_inRepStart = true;	// we're gonna send the START
385
	  // don't enable the interrupt. We'll generate the start, but we 
386
	  // avoid handling the interrupt until we're in the next transaction,
387
	  // at the point where we would normally issue the start.
388
	  TWCR = _BV(TWINT) | _BV(TWSTA)| _BV(TWEN) ;
389
	  twi_state = TWI_READY;
390
	}
391
      }
392
      break;
393
    case TW_MT_SLA_NACK:  // address sent, nack received
394
      twi_error = TW_MT_SLA_NACK;
395
      twi_stop();
396
      break;
397
    case TW_MT_DATA_NACK: // data sent, nack received
398
      twi_error = TW_MT_DATA_NACK;
399
      twi_stop();
400
      break;
401
    case TW_MT_ARB_LOST: // lost bus arbitration
402
      twi_error = TW_MT_ARB_LOST;
403
      twi_releaseBus();
404
      break;
405
 
406
    // Master Receiver
407
    case TW_MR_DATA_ACK: // data received, ack sent
408
      // put byte into buffer
409
      twi_masterBuffer[twi_masterBufferIndex++] = TWDR;
410
    case TW_MR_SLA_ACK:  // address sent, ack received
411
      // ack if more bytes are expected, otherwise nack
412
      if(twi_masterBufferIndex < twi_masterBufferLength){
413
        twi_reply(1);
414
      }else{
415
        twi_reply(0);
416
      }
417
      break;
418
    case TW_MR_DATA_NACK: // data received, nack sent
419
      // put final byte into buffer
420
      twi_masterBuffer[twi_masterBufferIndex++] = TWDR;
421
	if (twi_sendStop)
422
          twi_stop();
423
	else {
424
	  twi_inRepStart = true;	// we're gonna send the START
425
	  // don't enable the interrupt. We'll generate the start, but we 
426
	  // avoid handling the interrupt until we're in the next transaction,
427
	  // at the point where we would normally issue the start.
428
	  TWCR = _BV(TWINT) | _BV(TWSTA)| _BV(TWEN) ;
429
	  twi_state = TWI_READY;
430
	}    
431
	break;
432
    case TW_MR_SLA_NACK: // address sent, nack received
433
      twi_stop();
434
      break;
435
    // TW_MR_ARB_LOST handled by TW_MT_ARB_LOST case
436
 
437
    // Slave Receiver
438
    case TW_SR_SLA_ACK:   // addressed, returned ack
439
    case TW_SR_GCALL_ACK: // addressed generally, returned ack
440
    case TW_SR_ARB_LOST_SLA_ACK:   // lost arbitration, returned ack
441
    case TW_SR_ARB_LOST_GCALL_ACK: // lost arbitration, returned ack
442
      // enter slave receiver mode
443
      twi_state = TWI_SRX;
444
      // indicate that rx buffer can be overwritten and ack
445
      twi_rxBufferIndex = 0;
446
      twi_reply(1);
447
      break;
448
    case TW_SR_DATA_ACK:       // data received, returned ack
449
    case TW_SR_GCALL_DATA_ACK: // data received generally, returned ack
450
      // if there is still room in the rx buffer
451
      if(twi_rxBufferIndex < TWI_BUFFER_LENGTH){
452
        // put byte in buffer and ack
453
        twi_rxBuffer[twi_rxBufferIndex++] = TWDR;
454
        twi_reply(1);
455
      }else{
456
        // otherwise nack
457
        twi_reply(0);
458
      }
459
      break;
460
    case TW_SR_STOP: // stop or repeated start condition received
461
      // put a null char after data if there's room
462
      if(twi_rxBufferIndex < TWI_BUFFER_LENGTH){
463
        twi_rxBuffer[twi_rxBufferIndex] = '\0';
464
      }
465
      // sends ack and stops interface for clock stretching
466
      twi_stop();
467
      // callback to user defined callback
468
      twi_onSlaveReceive(twi_rxBuffer, twi_rxBufferIndex);
469
      // since we submit rx buffer to "wire" library, we can reset it
470
      twi_rxBufferIndex = 0;
471
      // ack future responses and leave slave receiver state
472
      twi_releaseBus();
473
      break;
474
    case TW_SR_DATA_NACK:       // data received, returned nack
475
    case TW_SR_GCALL_DATA_NACK: // data received generally, returned nack
476
      // nack back at master
477
      twi_reply(0);
478
      break;
479
 
480
    // Slave Transmitter
481
    case TW_ST_SLA_ACK:          // addressed, returned ack
482
    case TW_ST_ARB_LOST_SLA_ACK: // arbitration lost, returned ack
483
      // enter slave transmitter mode
484
      twi_state = TWI_STX;
485
      // ready the tx buffer index for iteration
486
      twi_txBufferIndex = 0;
487
      // set tx buffer length to be zero, to verify if user changes it
488
      twi_txBufferLength = 0;
489
      // request for txBuffer to be filled and length to be set
490
      // note: user must call twi_transmit(bytes, length) to do this
491
      twi_onSlaveTransmit();
492
      // if they didn't change buffer & length, initialize it
493
      if(0 == twi_txBufferLength){
494
        twi_txBufferLength = 1;
495
        twi_txBuffer[0] = 0x00;
496
      }
497
      // transmit first byte from buffer, fall
498
    case TW_ST_DATA_ACK: // byte sent, ack returned
499
      // copy data to output register
500
      TWDR = twi_txBuffer[twi_txBufferIndex++];
501
      // if there is more to send, ack, otherwise nack
502
      if(twi_txBufferIndex < twi_txBufferLength){
503
        twi_reply(1);
504
      }else{
505
        twi_reply(0);
506
      }
507
      break;
508
    case TW_ST_DATA_NACK: // received nack, we are done 
509
    case TW_ST_LAST_DATA: // received ack, but we are done already!
510
      // ack future responses
511
      twi_reply(1);
512
      // leave slave receiver state
513
      twi_state = TWI_READY;
514
      break;
515
 
516
    // All
517
    case TW_NO_INFO:   // no state information
518
      break;
519
    case TW_BUS_ERROR: // bus error, illegal stop/start
520
      twi_error = TW_BUS_ERROR;
521
      twi_stop();
522
      break;
523
  }
524
}
525