-
Notifications
You must be signed in to change notification settings - Fork 0
/
I2C.cpp
447 lines (397 loc) · 12.6 KB
/
I2C.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
/*
I2C.cpp - a free library for I2C communication of Arduino Nano or Mega. I haven't
tested it on other boards but any one uses ATmega48A/PA/88A/PA/168A/PA/328/P
or Atmel ATmega640/V-1280/V-1281/V-2560/V-2561/V chip should work. Please note
that this library needs the 8-bit Timer/Counter0. It is not recommended to put
these functions in an interrupt routing. And sometimes the delay() blocks this
library.
Please refer to https://longnight975551865.wordpress.com/2018/02/11/write-your-own-i%c2%b2c-library/ for more information.
Feedback and contribution is welcome!
Version 1.2
* add a marco for timeout, so the user can set it to false to disable the timeout
Version 1.1
* added timeout function which ensures the program won't hang up. Please note
the timeout() function uses the 8-bit Timer/Counter0.
* added a new requestFrom() that overloaded the previous one. The new requestFrom()
takes a user-defined array and its index and stores data in the specified location
of this array.
-------------------------------------
Created by Yudi Ren, Feb 1, 2018.
renyudicn@outlook.com
Version 1.0
*/
#include "I2C.h"
#include <Arduino.h>
//buffer
volatile uint8_t rxBuffer[RX_BUFFER_SIZE];
volatile uint8_t rxBufferIndex;
volatile uint8_t rxBufferLength;
volatile bool isTimeout = false;
/*
Initialise the I2C interface
@param selfAddress: the self selfAddress
@param i2cFreq: the I2C bus clock frequency, default is 100, unit KHz
@param slave: does this device work as a slave, default is false
@param generalCall: does this device response to general call, default is false
@param interrupt: does this device use I2C interrupt,default is false
*/
void TWI::I2CSetup(uint8_t selfAddress, int i2cFreq, bool slave, bool generalCall, bool interrupt){
//turn on the internal pull-up resistor
pinMode(SDA, INPUT_PULLUP);
pinMode(SCL, INPUT_PULLUP);
/*
The formula to calculate the SCL freq is on p212 of the datasheet of
the ATMEL328p.
*/
TWBR = (CPU_FREQ/i2cFreq/1000-16)/2;
//set the address
if(generalCall)
TWAR = (selfAddress<<1) | RESPOND_GC;
else
TWAR = (selfAddress<<1) | NOT_RESPOND_GC;
if(slave)
TWCR = (_BV(TWEA)) | (_BV(TWEN));
if(interrupt){
TWCR |= _BV(TWIE);
sei();
}
#if TIMEOUT
timeoutSetup();
#endif
rxBufferIndex = 0;
rxBufferLength = 0;
}
/*
Change the I2C bus clock frequency
@param freq: I2C bus frequency, unit is KHz
*/
void TWI::setFreq(int freq){
TWBR = (CPU_FREQ/freq/1000-16)/2;
}
/*
A switch for I2C interface Interrupt
@param on: on and off of the interrupt
*/
void TWI::interrupt(bool on){
if(on) //enable the TWI interrupt
TWCR |= _BV(TWIE);
else //switch off the TWI interrupt
TWCR &= (~(_BV(TWIE)));
}
/*
Master sends START information, slave address and WRITE/READ bit
@param address: slave address
@param type: WRITE or READ, predefined in I2C.h file
@param repeatStart: whether it's a repeat start
@return whether the operation is successful
*/
bool TWI::startTrans(uint8_t address, uint8_t type, bool repeatStart){
//send start condition
TWCR = (_BV(TWINT)) | (_BV(TWSTA)) | (_BV(TWEN));
#if TIMEOUT
waitingForComplete();
#else
while (!(TWCR & (_BV(TWINT))));
#endif
uint8_t status = TWSR & STATUS_CODE_MASK;
if(!repeatStart && status != START){
error(START);
return false;
}else if(repeatStart && status != RE_START){
error(RE_START);
return false;
}
//send the address and WRITE/READ bit
switch(type){
case WRITE:
TWDR = (address<<1) | WRITE;
TWCR = (_BV(TWINT)) | (_BV(TWEN));
#if TIMEOUT
waitingForComplete();
#else
while (!(TWCR & (_BV(TWINT))));
#endif
if((TWSR & STATUS_CODE_MASK) != MT_SLA_W_ACK){
error(MT_SLA_W_ACK);
return false;
}
break;
case READ:
TWDR = (address<<1) | READ;
TWCR = (_BV(TWINT)) | (_BV(TWEN));
#if TIMEOUT
waitingForComplete();
#else
while (!(TWCR & (_BV(TWINT))));
#endif
if((TWSR & STATUS_CODE_MASK) != MR_SLA_R_ACK){
error(MR_SLA_R_ACK);
return false;
}
break;
}
return true;
}
/*
Master writes data to the slave, this function can only send one byte at a
time, if you want to use burst write mode, just set the stop parameter to false
@param data: data to be sent
@param stop: does it send STOP signal
*/
void TWI::write(uint8_t data, bool stop){
TWDR = data;
TWCR = (_BV(TWINT)) | (_BV(TWEN));
#if TIMEOUT
waitingForComplete();
#else
while (!(TWCR & (_BV(TWINT))));
#endif
if((TWSR & STATUS_CODE_MASK) != MT_DATA_ACK)
error(MT_DATA_ACK);
if(stop)
stopTrans();
}
/*
Master request data from the slave. It will send a START signal so you need
to specify whether it's a repeat start
@param slaveAddress: the slave address
@param num: number of bytes requested from the slave, it should be less than
RX_BUFFER_SIZE
@param stop: does it send a STOP signal
@param repeatStart: is this a repeat start
*/
void TWI::requestFrom(uint8_t slaveAddress, uint8_t num, bool stop, bool repeatStart){
//initialise the buffer
rxBufferLength = num;
rxBufferIndex = 0;
startTrans(slaveAddress,READ,repeatStart);
//if the requested number of bytes is larger than RX_BUFFER_SIZE,
//truncate it to RX_BUFFER_SIZE
if(num>RX_BUFFER_SIZE)
num = RX_BUFFER_SIZE;
for(uint8_t n=0;n<num-1;n++){
TWCR = (_BV(TWEA)) | (_BV(TWINT)) | (_BV(TWEN));
#if TIMEOUT
waitingForComplete();
#else
while (!(TWCR & (_BV(TWINT))));
#endif
if((TWSR & STATUS_CODE_MASK) != MR_DATA_ACK)
error(MR_DATA_ACK);
rxBuffer[n] = TWDR;
}
//last byte, no TWEA (generate NACK)
TWCR = (_BV(TWINT)) | (_BV(TWEN));
#if TIMEOUT
waitingForComplete();
#else
while (!(TWCR & (_BV(TWINT))));
#endif
if((TWSR & STATUS_CODE_MASK) != MR_DATA_NACK)
error(MR_DATA_NACK);
rxBuffer[num-1] = TWDR;
if(stop)
stopTrans();
}
/*
Master request data from the slave. It will send a START signal so you need
to specify whether it's a repeat start. You can store the data in a user-defined buffer and specify the
the index. Note this will modify the value of the index.
@param slaveAddress: the slave address
@param num: number of bytes requested from the slave, it should be less than
RX_BUFFER_SIZE
@param stop: does it send a STOP signal
@param repeatStart: is this a repeat start
@param outSideBuffer: save the data to a user-defined buffer array
@param outSideBufferIndex: store data from this index. This will modify the original variable
*/
void TWI::requestFrom(uint8_t slaveAddress, uint8_t num, bool stop, int & outSideBufferIndex, uint8_t* outSideBuffer, bool repeatStart){
//initialise the buffer
rxBufferLength = num;
rxBufferIndex = 0;
startTrans(slaveAddress,READ,repeatStart);
for(uint8_t n=0;n<num-1;n++){
TWCR = (_BV(TWEA)) | (_BV(TWINT)) | (_BV(TWEN));
#if TIMEOUT
waitingForComplete();
#else
while (!(TWCR & (_BV(TWINT))));
#endif
if((TWSR & STATUS_CODE_MASK) != MR_DATA_ACK)
error(MR_DATA_ACK);
outSideBuffer[outSideBufferIndex++] = TWDR;
}
//last byte, no TWEA (generate NACK)
TWCR = (_BV(TWINT)) | (_BV(TWEN));
#if TIMEOUT
waitingForComplete();
#else
while (!(TWCR & (_BV(TWINT))));
#endif
if((TWSR & STATUS_CODE_MASK) != MR_DATA_NACK)
error(MR_DATA_NACK);
outSideBuffer[outSideBufferIndex++] = TWDR;
if(stop)
stopTrans();
}
/*
Read the receive buffer
@return one byte in the buffer
*/
uint8_t TWI::readBuffer(){
if(rxBufferLength > 0){
rxBufferLength--;
return rxBuffer[rxBufferIndex++];
}
return 0;
}
/*
get the rxBuffer array
@return the rxBuffer array pointer
*/
uint8_t* TWI::getBuffer(){
return rxBuffer;
}
/*
Send STOP signal
*/
void TWI::stopTrans(){
TWCR = (_BV(TWINT))|(_BV(TWEN)) | (_BV(TWSTO));
}
/*
Function to print the status code it should be when an error happens
*/
void TWI::error(uint8_t type,uint8_t info){
switch(type){
case START:
Serial.println("START ");
break;
case RE_START:
Serial.println("RE_START");
break;
case ARB_LOST:
Serial.println("ARB_LOST");
break;
case MT_SLA_W_ACK:
Serial.println("MT_SLA_W_ACK ");
break;
case MT_SLA_W_NACK:
Serial.println("MT_SLA_W_NACK");
break;
case MT_DATA_ACK:
Serial.println("MT_DATA_ACK");
break;
case MT_DATA_NACK:
Serial.println("MT_DATA_NACK");
break;
case MR_SLA_R_ACK:
Serial.print("MR_SLA_R_ACK ");
Serial.println(info,HEX);
break;
case MR_SLA_R_NACK:
Serial.println("MR_SLA_R_NACK");
break;
case MR_DATA_ACK:
Serial.println("MR_DATA_ACK");
break;
case MR_DATA_NACK:
Serial.println("MR_DATA_NACK");
break;
case SR_AD_RECEIVED:
Serial.println("SR_AD_RECEIVED");
break;
case SR_ARB_AD:
Serial.println("SR_ARB_AD");
break;
case GENERAL_CALL:
Serial.println("GENERAL_CALL");
break;
case SR_ARB_GC:
Serial.println("SR_ARB_GC");
break;
case SR_PRE_AD_DATA_ACK:
Serial.println("SR_PRE_AD_DATA_ACK");
break;
case SR_PRE_AD_DATA_NACK:
Serial.println("SR_PRE_AD_DATA_NACK");
break;
case SR_PRE_GC_DATA_ACK:
Serial.println("SR_PRE_GC_DATA_ACK");
break;
case SR_PRE_GC_DATA_NACK:
Serial.println("SR_PRE_GC_DATA_NACK");
break;
case SR_STOP:
Serial.println("SR_STOP");
break;
default:
Serial.println("Unknown error");
break;
}
}
/*
Slave receives data from a master. To use this function, you need to initialise
the chip to a slave by using the I2CSetup(). One needs to make sure that the
number of bytes to be sent should not exceed RX_BUFFER_SIZE.
*/
void TWI::receive(){
uint8_t backup = TWCR;
//if the own address has been received
uint8_t status = TWSR & STATUS_CODE_MASK;
if(status == SR_AD_RECEIVED || status == GENERAL_CALL){
TWCR = (_BV(TWINT)) | (_BV(TWEN)) | (_BV(TWEA));
//initialise the buffer
rxBufferIndex = 0;
rxBufferLength = 0;
#if TIMEOUT
waitingForComplete();
#else
while (!(TWCR & (_BV(TWINT))));
#endif
status = TWSR & STATUS_CODE_MASK;
while(status == SR_PRE_AD_DATA_ACK || status == SR_PRE_GC_DATA_ACK){
rxBuffer[rxBufferIndex++] = TWDR;
rxBufferLength++;
TWCR = (_BV(TWINT)) | (_BV(TWEN)) | (_BV(TWEA));
#if TIMEOUT
waitingForComplete();
#else
while (!(TWCR & (_BV(TWINT))));
#endif
status = TWSR & STATUS_CODE_MASK;
}
//if received a STOP signal
if(status == SR_STOP){
rxBufferIndex = 0;
}else{
error(status);
}
}
TWCR = backup;
}
/*
A function to wait for the transmission complete.
*/
void TWI::waitingForComplete(){
TCNT0 = 0x00; //initialize the counter
TIMSK0 = _BV(OCIE0A); //enable the timeout interrupt
while(!(TWCR & (_BV(TWINT))) && !isTimeout);
TIMSK0 = 0x00; //disable the timeout interrupt
isTimeout = false;
}
/*
Set timeout. Change the value of the OUTPUT_COMPARE_COUNTER_0 to modify the
timeout time. The default is 1ms. It uses the 8-bit Timer/Counter0.
*/
void TWI::timeoutSetup(){
cli(); //disable the global interrupt
TCCR0A = _BV(WGM01); //CTC mode
TCCR0B = (_BV(CS02)) | (_BV(CS00)); //perscaler = 1024
OCR0A = OUTPUT_COMPARE_COUNTER_0*TIMEOUT_PERIOD;
//we don't enable this interrupt now
sei(); //enable global interrupt
}
//timeout interrupt
ISR(TIMER0_COMPA_vect){
isTimeout = true;
}