Project

General

Profile

Statistics
| Revision:

root / branches / wireless / code / projects / libdragonfly / i2c.c @ 1624

History | View | Annotate | Download (11.3 KB)

1
/**
2
 * Copyright (c) 2007 Colony Project
3
 * 
4
 * Permission is hereby granted, free of charge, to any person
5
 * obtaining a copy of this software and associated documentation
6
 * files (the "Software"), to deal in the Software without
7
 * restriction, including without limitation the rights to use,
8
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
9
 * copies of the Software, and to permit persons to whom the
10
 * Software is furnished to do so, subject to the following
11
 * conditions:
12
 * 
13
 * The above copyright notice and this permission notice shall be
14
 * included in all copies or substantial portions of the Software.
15
 * 
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
18
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
20
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23
 * OTHER DEALINGS IN THE SOFTWARE.
24
 **/
25

    
26

    
27
/**
28
 * @file i2c.c
29
 * @brief Implemenation of I2C communications protocol
30
 * 
31
 * In the case where you have master sends and then a master request to the same
32
 * address, you will not give up control of the line because the send and
33
 * request addresses are seen as different addresses. In between it will send a
34
 * restart but will not give up the line.
35
 *
36
 * @author CMU Robotics Club, Kevin Woo, Sursh Nidhiry
37
 * @bug Not tested.
38
 */
39

    
40
#include <avr/interrupt.h>
41
#include <util/twi.h>
42

    
43
#include "i2c.h"
44
#include "ring_buffer.h"
45

    
46
//NOTE: this is here just to provide colony error codes, it can be safely removed
47
// for use in another project
48
#include <dragonfly_lib.h>
49

    
50
/**
51
 * @defgroup i2c I2C 
52
 *
53
 * @brief Provides Inter-Interconnected-Communications (I2C)
54
 * 
55
 * Initiates I2C functions on an ATMega128 which has a fully hardware Two Wire 
56
 * Interface (TWI) module. Any Atmel chip with this hardware should be able to
57
 * use the software.
58
 *
59
 * This code will operate in a multi-master enviornment and can be either a
60
 * slave or a master at any time (as long as they are not one or the other at
61
 * the moment. You can queue up multiple transmission modes in the buffer up to 
62
 * the buffer size. The buffer is implemented as a ring buffer.
63
 *
64
 * It is implemented using callback functions. Whenever you want to send a packet
65
 * you can call the built in send function (as a master) and it will send an array
66
 * of bytes. Master recieve and slave send/receive are all handled by the call back
67
 * functions. It is up to the end user to create functions that will handle the
68
 * receiving of packets. Their functions will be called with every byte recieved
69
 * so you must either buffer the inputs or handle each one separately.
70
 *
71
 * On errors we will simply flush the entire buffer.
72
 * 
73
 * For information on how I2C operates, read the wikipedia article
74
 * http://en.wikipedia.org/wiki/I2c
75
 * for a good explanation of how it works.
76
 * @{
77
 */
78

    
79
/** 
80
 * @brief Set bit rate 12 = 100kbit/s (max speed setting is 10 for an
81
 *  8 MHz clock). It is a divider, so the lower the number the faster the speed.
82
 */
83
#define I2C_BIT_RATE_DIVIDER 0x0C
84

    
85
unsigned char i2c_initd=0;
86

    
87
static int start_flag;
88

    
89
static fun_mrecv_t master_recv_function;
90
static fun_srecv_t slave_recv_function;
91
static fun_send_t slave_send_function;
92

    
93
RING_BUFFER_NEW(i2c_buffer, 128, char, i2c_write_buff, i2c_addr_buff);
94

    
95

    
96
/**
97
 * @brief Initializes the i2c module.
98
 *
99
 * Initializes the I2C module to start listening on the i2c lines. If the callback functions
100
 * are not set to null they will be called when that transmission mode is called. The address
101
 * is your address that you will listen to when you are not the master.
102
 *
103
 * @param addr                         Your address on the I2C bus.
104
 * @param master_recv         The address of the function to call when you receive a byte when you are a
105
 *                            master.
106
 * @param slave_recv         The address of the function to call when you are a slave you receive data
107
 *                                                                from the master
108
 * @param slave_send                The address of the function to call when you are a slave and the master
109
 *                                                                requests data from you.
110
 *
111
 * @return 0 for success, nonzero for failure
112
 **/
113
int i2c_init(char addr, fun_mrecv_t master_recv, fun_srecv_t slave_recv, fun_send_t slave_send) {
114

    
115
    if(i2c_initd)
116
      return ERROR_INIT_ALREADY_INITD;
117

    
118

    
119
    master_recv_function = master_recv;
120
    slave_recv_function = slave_recv;
121
    slave_send_function = slave_send;
122

    
123
    RING_BUFFER_CLEAR(i2c_write_buff);
124
    RING_BUFFER_CLEAR(i2c_addr_buff);
125
  
126
    /* enables twi interrupt, automatic ack sending, and all twi hardware */
127
    TWCR =  (_BV(TWEA) | _BV(TWEN) | _BV(TWIE));
128

    
129
    /* sets the bit rate of data transmission */
130
    TWBR = I2C_BIT_RATE_DIVIDER;
131

    
132
    /* sets the address (it is stored in the 7 most significant bits) and allows
133
     * global messages to be accepted */
134
    TWAR = (addr << 1) | 1;
135
  
136
    i2c_initd = 1;
137
    return 0;
138
}
139

    
140
/**
141
 * @brief Sends a byte array over I2C as a master
142
 *
143
 * Will perform a send over I2C to the destination from data for the ammount of
144
 * bytes that bytes is.
145
 *
146
 * @param dest                Destination address of the data on the I2C bus.
147
 * @param data         The pointer to the byte array of data
148
 * @param bytes        The amount of bytes long that the byte array is. This is how
149
 *                                                many bytes from the array that the function will send.
150
 *
151
 * @return zero for success, nonzero for failure
152
 **/
153
int i2c_send(char dest, char *data, unsigned int bytes) {
154
    int i;
155

    
156
    if(!i2c_initd)
157
      return ERROR_LIBRARY_NOT_INITD;
158

    
159

    
160
    /* adding data to be sent to ring buffers is not atomic,
161
     * so disable interrupts */
162
    cli();
163
    for(i = 0; i < bytes; i++) {
164
        if(RING_BUFFER_FULL(i2c_write_buff)) {
165
            sei();
166
            return -1;
167
        }
168

    
169
        RING_BUFFER_ADD(i2c_write_buff, data[i]);
170
        RING_BUFFER_ADD(i2c_addr_buff, dest << 1);
171
    }
172
    
173
    /* re-enable the interrupts */
174
    sei();
175
    
176
    /* send the start bit, only if this device is not currently master */
177
    if(!start_flag) {
178
        start_flag = 1;
179
        TWCR |= _BV(TWSTA);
180
        TWCR |= _BV(TWINT);
181
    }
182
  
183
    return 0;
184
}
185
 
186
/**
187
 * @brief Send a master request to the destination
188
 *
189
 * Sends a request of data from the target address and calls
190
 * the callback function to handle data as it comes in. This function will
191
 * not work if the slave has not informationt to send or has nothing implemented
192
 * to send it.
193
 *
194
 * @param dest                The destination that we want to receive information from.
195
 *
196
 * @return 0 for success, nonzero for failure
197
 **/ 
198
int i2c_request(char dest) {
199
    if(!i2c_initd)
200
      return ERROR_LIBRARY_NOT_INITD;
201

    
202
    if(RING_BUFFER_FULL(i2c_write_buff))
203
        return -1;
204
  
205
    RING_BUFFER_ADD(i2c_write_buff, 0);
206
    RING_BUFFER_ADD(i2c_addr_buff, (dest << 1) | 1);
207
  
208
    if(!start_flag) {
209
        start_flag = 1;
210
        TWCR |= _BV(TWSTA);
211
        TWCR |= _BV(TWINT);
212
    }
213
  
214
    return 0;
215
}
216

    
217
/** @} **/
218
 
219
/**
220
 * @brief Interrupt to handle I2C interrupts from the I2C hardware.
221
 * 
222
 * Uses the status codes from the I2C register to handle the events
223
 * needed to advance in I2C stages. For instance, you will get a bit for
224
 * receiving a start ack, then a address ack, then a data ack, etc.
225
 * The events are handled in each switch case. The status codes are defined
226
 * by avr-gcc in /util/twi.h but are the same codes as the Atmel documentation.
227
 *
228
 * Bytes are sent by popping off the ring buffer. It also will keep track
229
 * of what modes the send is in.
230
 *
231
 * Errors are handled here as well.
232
 **/ 
233
ISR(TWI_vect) {
234
        static char data_to_send;
235
        static char addr_to_send = -1;
236
        char addr, statusCode;
237
  
238
        //Get status code (only upper 5 bits)
239
        statusCode = (TWSR & 0xF8);
240

    
241
    switch (statusCode) {
242
        //Start sent successfully
243
        case TW_START:
244
        case TW_REP_START:
245
            /* Send address and write
246
             * ring_buffer will not be empty */
247
            RING_BUFFER_REMOVE(i2c_addr_buff, addr_to_send);
248
            RING_BUFFER_REMOVE(i2c_write_buff, data_to_send);
249
            
250
            /* first send the address */
251
            TWDR = addr_to_send; 
252
            
253
            //Turn off start bits
254
            TWCR &= ~_BV(TWSTA);
255
            break;
256

    
257
        //Master Transmit - Address sent succesfully
258
        case TW_MT_SLA_ACK:
259
        //Send byte
260
            TWDR = data_to_send;
261
            PORTG &= ~_BV(PG2);
262
            break;
263
         
264
        //Master Transmit - Data sent succesfully
265
        case TW_MT_DATA_ACK:    
266
            //If there is still data to send
267
            if(!RING_BUFFER_EMPTY(i2c_write_buff)) {
268
                RING_BUFFER_PEEK(i2c_addr_buff, addr);
269
        
270
                //Still data for this address
271
                if (addr == addr_to_send) {
272
                    RING_BUFFER_REMOVE(i2c_addr_buff, addr);
273
                    RING_BUFFER_REMOVE(i2c_write_buff, TWDR);
274
                    break;
275
                //No more data for this address, data for another address -> resend start
276
                } else {
277
                    TWCR |= _BV(TWSTA);
278
                    break;
279
                }
280
            }
281
            /* there are no bytes to send */
282
            TWCR |= _BV(TWSTO);
283
            start_flag = 0;
284
            break; 
285
            
286
        //Master Transmit - Slave sends a nack, transmit is done
287
        case TW_MT_DATA_NACK:
288
            PORTG |= _BV(PG2);
289
            TWCR |= _BV(TWSTO);
290
            start_flag = 0;
291
            break;
292
    
293
        //Master Receive - Address sent succesfully
294
        case TW_MR_SLA_ACK:
295
            PORTG |= _BV(PG2);
296
            break;
297
            
298
        //Master Receive - Data received succesfully
299
        case TW_MR_DATA_ACK:
300
            if(master_recv_function) {
301
                if(!master_recv_function(TWDR)) {
302
                    TWCR &= ~_BV(TWEA);
303
                }
304
            }
305
            break;
306
            
307
        //Master Receive - Slave sends a nack, transmission is done    
308
        case TW_MR_DATA_NACK:
309
            TWCR |= _BV(TWEA);
310
      
311
            //If there is still data to send
312
            if(!RING_BUFFER_EMPTY(i2c_write_buff)) {
313
                TWCR |= _BV(TWSTA);
314
                break;
315
            }
316
      
317
            /* there are no bytes to send */
318
            TWCR |= _BV(TWSTO);
319
            start_flag = 0;  
320
            break;
321
    
322
        //Slave Transmit - Address received
323
        case TW_ST_SLA_ACK:
324
            break;
325
    
326
        //Slave Transmit - Nack received, no data requsted
327
        case TW_ST_DATA_NACK:
328
            break;
329
        
330
        //Slave Transmit - Data requested, ack received
331
        case TW_ST_DATA_ACK:
332
            if (slave_send_function) {
333
                TWDR = slave_send_function();
334
            }
335
            break;
336
    
337
        //Slave Receive - Address received  
338
        case TW_SR_SLA_ACK:
339
            break;
340
    
341
        //Slave Receive - Data received, ack returned
342
        case TW_SR_DATA_ACK:
343
            if(slave_recv_function) {
344
                slave_recv_function(TWDR);
345
            }
346
            
347
            break;
348
      
349
        //Stop sent  
350
        case TW_SR_STOP:
351
            break;
352
        
353
        //Problem on the bus, reset everything
354
        default:
355
            TWCR |= _BV(TWSTO);
356
            start_flag = 0;
357
            RING_BUFFER_CLEAR(i2c_write_buff);
358
            RING_BUFFER_CLEAR(i2c_addr_buff);          
359
    }
360
  
361
  /* Toggle TWINT so that it resets and executes the commands */
362
  TWCR |= _BV(TWINT);
363
}
364