-
Notifications
You must be signed in to change notification settings - Fork 99
/
I2Cdev.cpp
1437 lines (1259 loc) · 55.1 KB
/
I2Cdev.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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// I2Cdev library collection - Main I2C device class
// Abstracts bit and byte I2C R/W functions into a convenient class
// 2013-06-05 by Jeff Rowberg <[email protected]>
//
// Changelog:
// 2013-05-06 - add Francesco Ferrara's Fastwire v0.24 implementation with small modifications
// 2013-05-05 - fix issue with writing bit values to words (Sasquatch/Farzanegan)
// 2012-06-09 - fix major issue with reading > 32 bytes at a time with Arduino Wire
// - add compiler warnings when using outdated or IDE or limited I2Cdev implementation
// 2011-11-01 - fix write*Bits mask calculation (thanks sasquatch @ Arduino forums)
// 2011-10-03 - added automatic Arduino version detection for ease of use
// 2011-10-02 - added Gene Knight's NBWire TwoWire class implementation with small modifications
// 2011-08-31 - added support for Arduino 1.0 Wire library (methods are different from 0.x)
// 2011-08-03 - added optional timeout parameter to read* methods to easily change from default
// 2011-08-02 - added support for 16-bit registers
// - fixed incorrect Doxygen comments on some methods
// - added timeout value for read operations (thanks mem @ Arduino forums)
// 2011-07-30 - changed read/write function structures to return success or byte counts
// - made all methods static for multi-device memory savings
// 2011-07-28 - initial release
/* ============================================
I2Cdev device library code is placed under the MIT license
Copyright (c) 2013 Jeff Rowberg
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
===============================================
*/
#include "I2Cdev.h"
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
#ifdef I2CDEV_IMPLEMENTATION_WARNINGS
#if ARDUINO < 100
#warning Using outdated Arduino IDE with Wire library is functionally limiting.
#warning Arduino IDE v1.6.5+ with I2Cdev Fastwire implementation is recommended.
#warning This I2Cdev implementation does not support:
#warning - Repeated starts conditions
#warning - Timeout detection (some Wire requests block forever)
#elif ARDUINO == 100
#warning Using outdated Arduino IDE with Wire library is functionally limiting.
#warning Arduino IDE v1.6.5+ with I2Cdev Fastwire implementation is recommended.
#warning This I2Cdev implementation does not support:
#warning - Repeated starts conditions
#warning - Timeout detection (some Wire requests block forever)
#elif ARDUINO > 100
/*#warning Using current Arduino IDE with Wire library is functionally limiting.
#warning Arduino IDE v1.6.5+ with I2CDEV_BUILTIN_FASTWIRE implementation is recommended.
#warning This I2Cdev implementation does not support:
#warning - Timeout detection (some Wire requests block forever)*/
#endif
#endif
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
//#error The I2CDEV_BUILTIN_FASTWIRE implementation is known to be broken right now. Patience, Iago!
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE
#ifdef I2CDEV_IMPLEMENTATION_WARNINGS
#warning Using I2CDEV_BUILTIN_NBWIRE implementation may adversely affect interrupt detection.
#warning This I2Cdev implementation does not support:
#warning - Repeated starts conditions
#endif
// NBWire implementation based heavily on code by Gene Knight <[email protected]>
// Originally posted on the Arduino forum at http://arduino.cc/forum/index.php/topic,70705.0.html
// Originally offered to the i2cdevlib project at http://arduino.cc/forum/index.php/topic,68210.30.html
TwoWire Wire;
#endif
/** Default constructor.
*/
I2Cdev::I2Cdev() {
}
/** Read a single bit from an 8-bit device register.
* @param devAddr I2C slave device address
* @param regAddr Register regAddr to read from
* @param bitNum Bit position to read (0-7)
* @param data Container for single bit value
* @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
* @return Status of read operation (true = success)
*/
int8_t I2Cdev::readBit(uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint8_t *data, uint16_t timeout) {
uint8_t b;
uint8_t count = readByte(devAddr, regAddr, &b, timeout);
*data = b & (1 << bitNum);
return count;
}
/** Read a single bit from a 16-bit device register.
* @param devAddr I2C slave device address
* @param regAddr Register regAddr to read from
* @param bitNum Bit position to read (0-15)
* @param data Container for single bit value
* @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
* @return Status of read operation (true = success)
*/
int8_t I2Cdev::readBitW(uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint16_t *data, uint16_t timeout) {
uint16_t b;
uint8_t count = readWord(devAddr, regAddr, &b, timeout);
*data = b & (1 << bitNum);
return count;
}
/** Read multiple bits from an 8-bit device register.
* @param devAddr I2C slave device address
* @param regAddr Register regAddr to read from
* @param bitStart First bit position to read (0-7)
* @param length Number of bits to read (not more than 8)
* @param data Container for right-aligned value (i.e. '101' read from any bitStart position will equal 0x05)
* @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
* @return Status of read operation (true = success)
*/
int8_t I2Cdev::readBits(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint8_t *data, uint16_t timeout) {
// 01101001 read byte
// 76543210 bit numbers
// xxx args: bitStart=4, length=3
// 010 masked
// -> 010 shifted
uint8_t count, b;
if ((count = readByte(devAddr, regAddr, &b, timeout)) != 0) {
uint8_t mask = ((1 << length) - 1) << (bitStart - length + 1);
b &= mask;
b >>= (bitStart - length + 1);
*data = b;
}
return count;
}
/** Read multiple bits from a 16-bit device register.
* @param devAddr I2C slave device address
* @param regAddr Register regAddr to read from
* @param bitStart First bit position to read (0-15)
* @param length Number of bits to read (not more than 16)
* @param data Container for right-aligned value (i.e. '101' read from any bitStart position will equal 0x05)
* @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
* @return Status of read operation (1 = success, 0 = failure, -1 = timeout)
*/
int8_t I2Cdev::readBitsW(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint16_t *data, uint16_t timeout) {
// 1101011001101001 read byte
// fedcba9876543210 bit numbers
// xxx args: bitStart=12, length=3
// 010 masked
// -> 010 shifted
uint8_t count;
uint16_t w;
if ((count = readWord(devAddr, regAddr, &w, timeout)) != 0) {
uint16_t mask = ((1 << length) - 1) << (bitStart - length + 1);
w &= mask;
w >>= (bitStart - length + 1);
*data = w;
}
return count;
}
/** Read single byte from an 8-bit device register.
* @param devAddr I2C slave device address
* @param regAddr Register regAddr to read from
* @param data Container for byte value read from device
* @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
* @return Status of read operation (true = success)
*/
int8_t I2Cdev::readByte(uint8_t devAddr, uint8_t regAddr, uint8_t *data, uint16_t timeout) {
return readBytes(devAddr, regAddr, 1, data, timeout);
}
/** Read single word from a 16-bit device register.
* @param devAddr I2C slave device address
* @param regAddr Register regAddr to read from
* @param data Container for word value read from device
* @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
* @return Status of read operation (true = success)
*/
int8_t I2Cdev::readWord(uint8_t devAddr, uint8_t regAddr, uint16_t *data, uint16_t timeout) {
return readWords(devAddr, regAddr, 1, data, timeout);
}
/** Read multiple bytes from an 8-bit device register.
* @param devAddr I2C slave device address
* @param regAddr First register regAddr to read from
* @param length Number of bytes to read
* @param data Buffer to store read data in
* @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
* @return Number of bytes read (-1 indicates failure)
*/
int8_t I2Cdev::readBytes(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint8_t *data, uint16_t timeout) {
#ifdef I2CDEV_SERIAL_DEBUG
Serial.print("I2C (0x");
Serial.print(devAddr, HEX);
Serial.print(") reading ");
Serial.print(length, DEC);
Serial.print(" bytes from 0x");
Serial.print(regAddr, HEX);
Serial.print("...");
#endif
int8_t count = 0;
uint32_t t1 = millis();
#if (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE)
#if (ARDUINO < 100)
// Arduino v00xx (before v1.0), Wire library
// I2C/TWI subsystem uses internal buffer that breaks with large data requests
// so if user requests more than BUFFER_LENGTH bytes, we have to do it in
// smaller chunks instead of all at once
for (uint8_t k = 0; k < length; k += min(length, BUFFER_LENGTH)) {
Wire.beginTransmission(devAddr);
Wire.send(regAddr);
Wire.endTransmission();
Wire.beginTransmission(devAddr);
Wire.requestFrom(devAddr, (uint8_t)min(length - k, BUFFER_LENGTH));
for (; Wire.available() && (timeout == 0 || millis() - t1 < timeout); count++) {
data[count] = Wire.receive();
#ifdef I2CDEV_SERIAL_DEBUG
Serial.print(data[count], HEX);
if (count + 1 < length) Serial.print(" ");
#endif
}
Wire.endTransmission();
}
#elif (ARDUINO == 100)
// Arduino v1.0.0, Wire library
// Adds standardized write() and read() stream methods instead of send() and receive()
// I2C/TWI subsystem uses internal buffer that breaks with large data requests
// so if user requests more than BUFFER_LENGTH bytes, we have to do it in
// smaller chunks instead of all at once
for (uint8_t k = 0; k < length; k += min(length, BUFFER_LENGTH)) {
Wire.beginTransmission(devAddr);
Wire.write(regAddr);
Wire.endTransmission();
Wire.beginTransmission(devAddr);
Wire.requestFrom(devAddr, (uint8_t)min(length - k, BUFFER_LENGTH));
for (; Wire.available() && (timeout == 0 || millis() - t1 < timeout); count++) {
data[count] = Wire.read();
#ifdef I2CDEV_SERIAL_DEBUG
Serial.print(data[count], HEX);
if (count + 1 < length) Serial.print(" ");
#endif
}
Wire.endTransmission();
}
#elif (ARDUINO > 100)
// Arduino v1.0.1+, Wire library
// Adds official support for repeated start condition, yay!
// I2C/TWI subsystem uses internal buffer that breaks with large data requests
// so if user requests more than BUFFER_LENGTH bytes, we have to do it in
// smaller chunks instead of all at once
for (uint8_t k = 0; k < length; k += min(length, BUFFER_LENGTH)) {
Wire.beginTransmission(devAddr);
Wire.write(regAddr);
Wire.endTransmission();
Wire.beginTransmission(devAddr);
Wire.requestFrom(devAddr, (uint8_t)min(length - k, BUFFER_LENGTH));
for (; Wire.available() && (timeout == 0 || millis() - t1 < timeout); count++) {
data[count] = Wire.read();
#ifdef I2CDEV_SERIAL_DEBUG
Serial.print(data[count], HEX);
if (count + 1 < length) Serial.print(" ");
#endif
}
}
#endif
#elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE)
// Fastwire library
// no loop required for fastwire
uint8_t status = Fastwire::readBuf(devAddr << 1, regAddr, data, length);
if (status == 0) {
count = length; // success
} else {
count = -1; // error
}
#endif
// check for timeout
if (timeout > 0 && millis() - t1 >= timeout && count < length) count = -1; // timeout
#ifdef I2CDEV_SERIAL_DEBUG
Serial.print(". Done (");
Serial.print(count, DEC);
Serial.println(" read).");
#endif
return count;
}
/** Read multiple words from a 16-bit device register.
* @param devAddr I2C slave device address
* @param regAddr First register regAddr to read from
* @param length Number of words to read
* @param data Buffer to store read data in
* @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
* @return Number of words read (-1 indicates failure)
*/
int8_t I2Cdev::readWords(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint16_t *data, uint16_t timeout) {
#ifdef I2CDEV_SERIAL_DEBUG
Serial.print("I2C (0x");
Serial.print(devAddr, HEX);
Serial.print(") reading ");
Serial.print(length, DEC);
Serial.print(" words from 0x");
Serial.print(regAddr, HEX);
Serial.print("...");
#endif
int8_t count = 0;
uint32_t t1 = millis();
#if (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE)
#if (ARDUINO < 100)
// Arduino v00xx (before v1.0), Wire library
// I2C/TWI subsystem uses internal buffer that breaks with large data requests
// so if user requests more than BUFFER_LENGTH bytes, we have to do it in
// smaller chunks instead of all at once
for (uint8_t k = 0; k < length * 2; k += min(length * 2, BUFFER_LENGTH)) {
Wire.beginTransmission(devAddr);
Wire.send(regAddr);
Wire.endTransmission();
Wire.beginTransmission(devAddr);
Wire.requestFrom(devAddr, (uint8_t)(length * 2)); // length=words, this wants bytes
bool msb = true; // starts with MSB, then LSB
for (; Wire.available() && count < length && (timeout == 0 || millis() - t1 < timeout);) {
if (msb) {
// first byte is bits 15-8 (MSb=15)
data[count] = Wire.receive() << 8;
} else {
// second byte is bits 7-0 (LSb=0)
data[count] |= Wire.receive();
#ifdef I2CDEV_SERIAL_DEBUG
Serial.print(data[count], HEX);
if (count + 1 < length) Serial.print(" ");
#endif
count++;
}
msb = !msb;
}
Wire.endTransmission();
}
#elif (ARDUINO == 100)
// Arduino v1.0.0, Wire library
// Adds standardized write() and read() stream methods instead of send() and receive()
// I2C/TWI subsystem uses internal buffer that breaks with large data requests
// so if user requests more than BUFFER_LENGTH bytes, we have to do it in
// smaller chunks instead of all at once
for (uint8_t k = 0; k < length * 2; k += min(length * 2, BUFFER_LENGTH)) {
Wire.beginTransmission(devAddr);
Wire.write(regAddr);
Wire.endTransmission();
Wire.beginTransmission(devAddr);
Wire.requestFrom(devAddr, (uint8_t)(length * 2)); // length=words, this wants bytes
bool msb = true; // starts with MSB, then LSB
for (; Wire.available() && count < length && (timeout == 0 || millis() - t1 < timeout);) {
if (msb) {
// first byte is bits 15-8 (MSb=15)
data[count] = Wire.read() << 8;
} else {
// second byte is bits 7-0 (LSb=0)
data[count] |= Wire.read();
#ifdef I2CDEV_SERIAL_DEBUG
Serial.print(data[count], HEX);
if (count + 1 < length) Serial.print(" ");
#endif
count++;
}
msb = !msb;
}
Wire.endTransmission();
}
#elif (ARDUINO > 100)
// Arduino v1.0.1+, Wire library
// Adds official support for repeated start condition, yay!
// I2C/TWI subsystem uses internal buffer that breaks with large data requests
// so if user requests more than BUFFER_LENGTH bytes, we have to do it in
// smaller chunks instead of all at once
for (uint8_t k = 0; k < length * 2; k += min(length * 2, BUFFER_LENGTH)) {
Wire.beginTransmission(devAddr);
Wire.write(regAddr);
Wire.endTransmission();
Wire.beginTransmission(devAddr);
Wire.requestFrom(devAddr, (uint8_t)(length * 2)); // length=words, this wants bytes
bool msb = true; // starts with MSB, then LSB
for (; Wire.available() && count < length && (timeout == 0 || millis() - t1 < timeout);) {
if (msb) {
// first byte is bits 15-8 (MSb=15)
data[count] = Wire.read() << 8;
} else {
// second byte is bits 7-0 (LSb=0)
data[count] |= Wire.read();
#ifdef I2CDEV_SERIAL_DEBUG
Serial.print(data[count], HEX);
if (count + 1 < length) Serial.print(" ");
#endif
count++;
}
msb = !msb;
}
Wire.endTransmission();
}
#endif
#elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE)
// Fastwire library
// no loop required for fastwire
uint16_t intermediate[(uint8_t)length];
uint8_t status = Fastwire::readBuf(devAddr << 1, regAddr, (uint8_t *)intermediate, (uint8_t)(length * 2));
if (status == 0) {
count = length; // success
for (uint8_t i = 0; i < length; i++) {
data[i] = (intermediate[2*i] << 8) | intermediate[2*i + 1];
}
} else {
count = -1; // error
}
#endif
if (timeout > 0 && millis() - t1 >= timeout && count < length) count = -1; // timeout
#ifdef I2CDEV_SERIAL_DEBUG
Serial.print(". Done (");
Serial.print(count, DEC);
Serial.println(" read).");
#endif
return count;
}
/** write a single bit in an 8-bit device register.
* @param devAddr I2C slave device address
* @param regAddr Register regAddr to write to
* @param bitNum Bit position to write (0-7)
* @param value New bit value to write
* @return Status of operation (true = success)
*/
bool I2Cdev::writeBit(uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint8_t data) {
uint8_t b;
readByte(devAddr, regAddr, &b);
b = (data != 0) ? (b | (1 << bitNum)) : (b & ~(1 << bitNum));
return writeByte(devAddr, regAddr, b);
}
/** write a single bit in a 16-bit device register.
* @param devAddr I2C slave device address
* @param regAddr Register regAddr to write to
* @param bitNum Bit position to write (0-15)
* @param value New bit value to write
* @return Status of operation (true = success)
*/
bool I2Cdev::writeBitW(uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint16_t data) {
uint16_t w;
readWord(devAddr, regAddr, &w);
w = (data != 0) ? (w | (1 << bitNum)) : (w & ~(1 << bitNum));
return writeWord(devAddr, regAddr, w);
}
/** Write multiple bits in an 8-bit device register.
* @param devAddr I2C slave device address
* @param regAddr Register regAddr to write to
* @param bitStart First bit position to write (0-7)
* @param length Number of bits to write (not more than 8)
* @param data Right-aligned value to write
* @return Status of operation (true = success)
*/
bool I2Cdev::writeBits(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint8_t data) {
// 010 value to write
// 76543210 bit numbers
// xxx args: bitStart=4, length=3
// 00011100 mask byte
// 10101111 original value (sample)
// 10100011 original & ~mask
// 10101011 masked | value
uint8_t b;
if (readByte(devAddr, regAddr, &b) != 0) {
uint8_t mask = ((1 << length) - 1) << (bitStart - length + 1);
data <<= (bitStart - length + 1); // shift data into correct position
data &= mask; // zero all non-important bits in data
b &= ~(mask); // zero all important bits in existing byte
b |= data; // combine data with existing byte
return writeByte(devAddr, regAddr, b);
} else {
return false;
}
}
/** Write multiple bits in a 16-bit device register.
* @param devAddr I2C slave device address
* @param regAddr Register regAddr to write to
* @param bitStart First bit position to write (0-15)
* @param length Number of bits to write (not more than 16)
* @param data Right-aligned value to write
* @return Status of operation (true = success)
*/
bool I2Cdev::writeBitsW(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint16_t data) {
// 010 value to write
// fedcba9876543210 bit numbers
// xxx args: bitStart=12, length=3
// 0001110000000000 mask word
// 1010111110010110 original value (sample)
// 1010001110010110 original & ~mask
// 1010101110010110 masked | value
uint16_t w;
if (readWord(devAddr, regAddr, &w) != 0) {
uint16_t mask = ((1 << length) - 1) << (bitStart - length + 1);
data <<= (bitStart - length + 1); // shift data into correct position
data &= mask; // zero all non-important bits in data
w &= ~(mask); // zero all important bits in existing word
w |= data; // combine data with existing word
return writeWord(devAddr, regAddr, w);
} else {
return false;
}
}
/** Write single byte to an 8-bit device register.
* @param devAddr I2C slave device address
* @param regAddr Register address to write to
* @param data New byte value to write
* @return Status of operation (true = success)
*/
bool I2Cdev::writeByte(uint8_t devAddr, uint8_t regAddr, uint8_t data) {
return writeBytes(devAddr, regAddr, 1, &data);
}
/** Write single word to a 16-bit device register.
* @param devAddr I2C slave device address
* @param regAddr Register address to write to
* @param data New word value to write
* @return Status of operation (true = success)
*/
bool I2Cdev::writeWord(uint8_t devAddr, uint8_t regAddr, uint16_t data) {
return writeWords(devAddr, regAddr, 1, &data);
}
/** Write multiple bytes to an 8-bit device register.
* @param devAddr I2C slave device address
* @param regAddr First register address to write to
* @param length Number of bytes to write
* @param data Buffer to copy new data from
* @return Status of operation (true = success)
*/
bool I2Cdev::writeBytes(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint8_t* data) {
#ifdef I2CDEV_SERIAL_DEBUG
Serial.print("I2C (0x");
Serial.print(devAddr, HEX);
Serial.print(") writing ");
Serial.print(length, DEC);
Serial.print(" bytes to 0x");
Serial.print(regAddr, HEX);
Serial.print("...");
#endif
uint8_t status = 0;
#if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
Wire.beginTransmission(devAddr);
Wire.send((uint8_t) regAddr); // send address
#elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100)
Wire.beginTransmission(devAddr);
Wire.write((uint8_t) regAddr); // send address
#elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE)
Fastwire::beginTransmission(devAddr);
Fastwire::write(regAddr);
#endif
for (uint8_t i = 0; i < length; i++) {
#ifdef I2CDEV_SERIAL_DEBUG
Serial.print(data[i], HEX);
if (i + 1 < length) Serial.print(" ");
#endif
#if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
Wire.send((uint8_t) data[i]);
#elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100)
Wire.write((uint8_t) data[i]);
#elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE)
Fastwire::write((uint8_t) data[i]);
#endif
}
#if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
Wire.endTransmission();
#elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100)
status = Wire.endTransmission();
#elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE)
Fastwire::stop();
//status = Fastwire::endTransmission();
#endif
#ifdef I2CDEV_SERIAL_DEBUG
Serial.println(". Done.");
#endif
return status == 0;
}
/** Write multiple words to a 16-bit device register.
* @param devAddr I2C slave device address
* @param regAddr First register address to write to
* @param length Number of words to write
* @param data Buffer to copy new data from
* @return Status of operation (true = success)
*/
bool I2Cdev::writeWords(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint16_t* data) {
#ifdef I2CDEV_SERIAL_DEBUG
Serial.print("I2C (0x");
Serial.print(devAddr, HEX);
Serial.print(") writing ");
Serial.print(length, DEC);
Serial.print(" words to 0x");
Serial.print(regAddr, HEX);
Serial.print("...");
#endif
uint8_t status = 0;
#if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
Wire.beginTransmission(devAddr);
Wire.send(regAddr); // send address
#elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100)
Wire.beginTransmission(devAddr);
Wire.write(regAddr); // send address
#elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE)
Fastwire::beginTransmission(devAddr);
Fastwire::write(regAddr);
#endif
for (uint8_t i = 0; i < length * 2; i++) {
#ifdef I2CDEV_SERIAL_DEBUG
Serial.print(data[i], HEX);
if (i + 1 < length) Serial.print(" ");
#endif
#if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
Wire.send((uint8_t)(data[i] >> 8)); // send MSB
Wire.send((uint8_t)data[i++]); // send LSB
#elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100)
Wire.write((uint8_t)(data[i] >> 8)); // send MSB
Wire.write((uint8_t)data[i++]); // send LSB
#elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE)
Fastwire::write((uint8_t)(data[i] >> 8)); // send MSB
status = Fastwire::write((uint8_t)data[i++]); // send LSB
if (status != 0) break;
#endif
}
#if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
Wire.endTransmission();
#elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100)
status = Wire.endTransmission();
#elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE)
Fastwire::stop();
//status = Fastwire::endTransmission();
#endif
#ifdef I2CDEV_SERIAL_DEBUG
Serial.println(". Done.");
#endif
return status == 0;
}
/** Default timeout value for read operations.
* Set this to 0 to disable timeout detection.
*/
uint16_t I2Cdev::readTimeout = I2CDEV_DEFAULT_READ_TIMEOUT;
#if I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
// I2C library
//////////////////////
// Copyright(C) 2012
// Francesco Ferrara
// ferrara[at]libero[point]it
//////////////////////
/*
FastWire
- 0.24 added stop
- 0.23 added reset
This is a library to help faster programs to read I2C devices.
Copyright(C) 2012 Francesco Ferrara
occhiobello at gmail dot com
[used by Jeff Rowberg for I2Cdevlib with permission]
*/
boolean Fastwire::waitInt() {
int l = 250;
while (!(TWCR & (1 << TWINT)) && l-- > 0);
return l > 0;
}
void Fastwire::setup(int khz, boolean pullup) {
TWCR = 0;
#if defined(__AVR_ATmega168__) || defined(__AVR_ATmega8__) || defined(__AVR_ATmega328P__)
// activate internal pull-ups for twi (PORTC bits 4 & 5)
// as per note from atmega8 manual pg167
if (pullup) PORTC |= ((1 << 4) | (1 << 5));
else PORTC &= ~((1 << 4) | (1 << 5));
#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__)
// activate internal pull-ups for twi (PORTC bits 0 & 1)
if (pullup) PORTC |= ((1 << 0) | (1 << 1));
else PORTC &= ~((1 << 0) | (1 << 1));
#else
// activate internal pull-ups for twi (PORTD bits 0 & 1)
// as per note from atmega128 manual pg204
if (pullup) PORTD |= ((1 << 0) | (1 << 1));
else PORTD &= ~((1 << 0) | (1 << 1));
#endif
TWSR = 0; // no prescaler => prescaler = 1
TWBR = ((16000L / khz) - 16) / 2; // change the I2C clock rate
TWCR = 1 << TWEN; // enable twi module, no interrupt
}
// added by Jeff Rowberg 2013-05-07:
// Arduino Wire-style "beginTransmission" function
// (takes 7-bit device address like the Wire method, NOT 8-bit: 0x68, not 0xD0/0xD1)
byte Fastwire::beginTransmission(byte device) {
byte twst, retry;
retry = 2;
do {
TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO) | (1 << TWSTA);
if (!waitInt()) return 1;
twst = TWSR & 0xF8;
if (twst != TW_START && twst != TW_REP_START) return 2;
//Serial.print(device, HEX);
//Serial.print(" ");
TWDR = device << 1; // send device address without read bit (1)
TWCR = (1 << TWINT) | (1 << TWEN);
if (!waitInt()) return 3;
twst = TWSR & 0xF8;
} while (twst == TW_MT_SLA_NACK && retry-- > 0);
if (twst != TW_MT_SLA_ACK) return 4;
return 0;
}
byte Fastwire::writeBuf(byte device, byte address, byte *data, byte num) {
byte twst, retry;
retry = 2;
do {
TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO) | (1 << TWSTA);
if (!waitInt()) return 1;
twst = TWSR & 0xF8;
if (twst != TW_START && twst != TW_REP_START) return 2;
//Serial.print(device, HEX);
//Serial.print(" ");
TWDR = device & 0xFE; // send device address without read bit (1)
TWCR = (1 << TWINT) | (1 << TWEN);
if (!waitInt()) return 3;
twst = TWSR & 0xF8;
} while (twst == TW_MT_SLA_NACK && retry-- > 0);
if (twst != TW_MT_SLA_ACK) return 4;
//Serial.print(address, HEX);
//Serial.print(" ");
TWDR = address; // send data to the previously addressed device
TWCR = (1 << TWINT) | (1 << TWEN);
if (!waitInt()) return 5;
twst = TWSR & 0xF8;
if (twst != TW_MT_DATA_ACK) return 6;
for (byte i = 0; i < num; i++) {
//Serial.print(data[i], HEX);
//Serial.print(" ");
TWDR = data[i]; // send data to the previously addressed device
TWCR = (1 << TWINT) | (1 << TWEN);
if (!waitInt()) return 7;
twst = TWSR & 0xF8;
if (twst != TW_MT_DATA_ACK) return 8;
}
//Serial.print("\n");
return 0;
}
byte Fastwire::write(byte value) {
byte twst;
//Serial.println(value, HEX);
TWDR = value; // send data
TWCR = (1 << TWINT) | (1 << TWEN);
if (!waitInt()) return 1;
twst = TWSR & 0xF8;
if (twst != TW_MT_DATA_ACK) return 2;
return 0;
}
byte Fastwire::readBuf(byte device, byte address, byte *data, byte num) {
byte twst, retry;
retry = 2;
do {
TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO) | (1 << TWSTA);
if (!waitInt()) return 16;
twst = TWSR & 0xF8;
if (twst != TW_START && twst != TW_REP_START) return 17;
//Serial.print(device, HEX);
//Serial.print(" ");
TWDR = device & 0xfe; // send device address to write
TWCR = (1 << TWINT) | (1 << TWEN);
if (!waitInt()) return 18;
twst = TWSR & 0xF8;
} while (twst == TW_MT_SLA_NACK && retry-- > 0);
if (twst != TW_MT_SLA_ACK) return 19;
//Serial.print(address, HEX);
//Serial.print(" ");
TWDR = address; // send data to the previously addressed device
TWCR = (1 << TWINT) | (1 << TWEN);
if (!waitInt()) return 20;
twst = TWSR & 0xF8;
if (twst != TW_MT_DATA_ACK) return 21;
/***/
retry = 2;
do {
TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO) | (1 << TWSTA);
if (!waitInt()) return 22;
twst = TWSR & 0xF8;
if (twst != TW_START && twst != TW_REP_START) return 23;
//Serial.print(device, HEX);
//Serial.print(" ");
TWDR = device | 0x01; // send device address with the read bit (1)
TWCR = (1 << TWINT) | (1 << TWEN);
if (!waitInt()) return 24;
twst = TWSR & 0xF8;
} while (twst == TW_MR_SLA_NACK && retry-- > 0);
if (twst != TW_MR_SLA_ACK) return 25;
for (uint8_t i = 0; i < num; i++) {
if (i == num - 1)
TWCR = (1 << TWINT) | (1 << TWEN);
else
TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWEA);
if (!waitInt()) return 26;
twst = TWSR & 0xF8;
if (twst != TW_MR_DATA_ACK && twst != TW_MR_DATA_NACK) return twst;
data[i] = TWDR;
//Serial.print(data[i], HEX);
//Serial.print(" ");
}
//Serial.print("\n");
stop();
return 0;
}
void Fastwire::reset() {
TWCR = 0;
}
byte Fastwire::stop() {
TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO);
if (!waitInt()) return 1;
return 0;
}
#endif
#if I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE
// NBWire implementation based heavily on code by Gene Knight <[email protected]>
// Originally posted on the Arduino forum at http://arduino.cc/forum/index.php/topic,70705.0.html
// Originally offered to the i2cdevlib project at http://arduino.cc/forum/index.php/topic,68210.30.html
/*
call this version 1.0
Offhand, the only funky part that I can think of is in nbrequestFrom, where the buffer
length and index are set *before* the data is actually read. The problem is that these
are variables local to the TwoWire object, and by the time we actually have read the
data, and know what the length actually is, we have no simple access to the object's
variables. The actual bytes read *is* given to the callback function, though.
The ISR code for a slave receiver is commented out. I don't have that setup, and can't
verify it at this time. Save it for 2.0!
The handling of the read and write processes here is much like in the demo sketch code:
the process is broken down into sequential functions, where each registers the next as a
callback, essentially.
For example, for the Read process, twi_read00 just returns if TWI is not yet in a
ready state. When there's another interrupt, and the interface *is* ready, then it
sets up the read, starts it, and registers twi_read01 as the function to call after
the *next* interrupt. twi_read01, then, just returns if the interface is still in a
"reading" state. When the reading is done, it copies the information to the buffer,
cleans up, and calls the user-requested callback function with the actual number of
bytes read.
The writing is similar.
Questions, comments and problems can go to [email protected].
Thumbs Up!
Gene Knight
*/
uint8_t TwoWire::rxBuffer[NBWIRE_BUFFER_LENGTH];
uint8_t TwoWire::rxBufferIndex = 0;
uint8_t TwoWire::rxBufferLength = 0;
uint8_t TwoWire::txAddress = 0;
uint8_t TwoWire::txBuffer[NBWIRE_BUFFER_LENGTH];
uint8_t TwoWire::txBufferIndex = 0;
uint8_t TwoWire::txBufferLength = 0;
//uint8_t TwoWire::transmitting = 0;
void (*TwoWire::user_onRequest)(void);
void (*TwoWire::user_onReceive)(int);
static volatile uint8_t twi_transmitting;
static volatile uint8_t twi_state;
static uint8_t twi_slarw;
static volatile uint8_t twi_error;
static uint8_t twi_masterBuffer[TWI_BUFFER_LENGTH];
static volatile uint8_t twi_masterBufferIndex;
static uint8_t twi_masterBufferLength;
static uint8_t twi_rxBuffer[TWI_BUFFER_LENGTH];
static volatile uint8_t twi_rxBufferIndex;
//static volatile uint8_t twi_Interrupt_Continue_Command;
static volatile uint8_t twi_Return_Value;
static volatile uint8_t twi_Done;
void (*twi_cbendTransmissionDone)(int);
void (*twi_cbreadFromDone)(int);
void twi_init() {
// initialize state
twi_state = TWI_READY;
// activate internal pull-ups for twi
// as per note from atmega8 manual pg167
sbi(PORTC, 4);
sbi(PORTC, 5);
// initialize twi prescaler and bit rate
cbi(TWSR, TWPS0); // TWI Status Register - Prescaler bits
cbi(TWSR, TWPS1);
/* twi bit rate formula from atmega128 manual pg 204
SCL Frequency = CPU Clock Frequency / (16 + (2 * TWBR))
note: TWBR should be 10 or higher for master mode
It is 72 for a 16mhz Wiring board with 100kHz TWI */
TWBR = ((CPU_FREQ / TWI_FREQ) - 16) / 2; // bitrate register
// enable twi module, acks, and twi interrupt
TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA);
/* TWEN - TWI Enable Bit
TWIE - TWI Interrupt Enable
TWEA - TWI Enable Acknowledge Bit
TWINT - TWI Interrupt Flag
TWSTA - TWI Start Condition
*/
}
typedef struct {
uint8_t address;
uint8_t* data;
uint8_t length;
uint8_t wait;
uint8_t i;
} twi_Write_Vars;
twi_Write_Vars *ptwv = 0;
static void (*fNextInterruptFunction)(void) = 0;
void twi_Finish(byte bRetVal) {
if (ptwv) {
free(ptwv);
ptwv = 0;
}