You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1475 lines
56KB

  1. // I2Cdev library collection - Main I2C device class
  2. // Abstracts bit and byte I2C R/W functions into a convenient class
  3. // 2013-06-05 by Jeff Rowberg <jeff@rowberg.net>
  4. //
  5. // Changelog:
  6. // 2013-05-06 - add Francesco Ferrara's Fastwire v0.24 implementation with small modifications
  7. // 2013-05-05 - fix issue with writing bit values to words (Sasquatch/Farzanegan)
  8. // 2012-06-09 - fix major issue with reading > 32 bytes at a time with Arduino Wire
  9. // - add compiler warnings when using outdated or IDE or limited I2Cdev implementation
  10. // 2011-11-01 - fix write*Bits mask calculation (thanks sasquatch @ Arduino forums)
  11. // 2011-10-03 - added automatic Arduino version detection for ease of use
  12. // 2011-10-02 - added Gene Knight's NBWire TwoWire class implementation with small modifications
  13. // 2011-08-31 - added support for Arduino 1.0 Wire library (methods are different from 0.x)
  14. // 2011-08-03 - added optional timeout parameter to read* methods to easily change from default
  15. // 2011-08-02 - added support for 16-bit registers
  16. // - fixed incorrect Doxygen comments on some methods
  17. // - added timeout value for read operations (thanks mem @ Arduino forums)
  18. // 2011-07-30 - changed read/write function structures to return success or byte counts
  19. // - made all methods static for multi-device memory savings
  20. // 2011-07-28 - initial release
  21. /* ============================================
  22. I2Cdev device library code is placed under the MIT license
  23. Copyright (c) 2013 Jeff Rowberg
  24. Permission is hereby granted, free of charge, to any person obtaining a copy
  25. of this software and associated documentation files (the "Software"), to deal
  26. in the Software without restriction, including without limitation the rights
  27. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  28. copies of the Software, and to permit persons to whom the Software is
  29. furnished to do so, subject to the following conditions:
  30. The above copyright notice and this permission notice shall be included in
  31. all copies or substantial portions of the Software.
  32. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  33. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  34. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  35. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  36. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  37. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  38. THE SOFTWARE.
  39. ===============================================
  40. */
  41. #include "I2Cdev.h"
  42. #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_SBWIRE
  43. #ifdef I2CDEV_IMPLEMENTATION_WARNINGS
  44. #if ARDUINO < 100
  45. #warning Using outdated Arduino IDE with Wire library is functionally limiting.
  46. #warning Arduino IDE v1.6.5+ with I2Cdev Fastwire implementation is recommended.
  47. #warning This I2Cdev implementation does not support:
  48. #warning - Repeated starts conditions
  49. #warning - Timeout detection (some Wire requests block forever)
  50. #elif ARDUINO == 100
  51. #warning Using outdated Arduino IDE with Wire library is functionally limiting.
  52. #warning Arduino IDE v1.6.5+ with I2Cdev Fastwire implementation is recommended.
  53. #warning This I2Cdev implementation does not support:
  54. #warning - Repeated starts conditions
  55. #warning - Timeout detection (some Wire requests block forever)
  56. #elif ARDUINO > 100
  57. /*#warning Using current Arduino IDE with Wire library is functionally limiting.
  58. #warning Arduino IDE v1.6.5+ with I2CDEV_BUILTIN_FASTWIRE implementation is recommended.
  59. #warning This I2Cdev implementation does not support:
  60. #warning - Timeout detection (some Wire requests block forever)*/
  61. #endif
  62. #endif
  63. #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
  64. //#error The I2CDEV_BUILTIN_FASTWIRE implementation is known to be broken right now. Patience, Iago!
  65. #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE
  66. #ifdef I2CDEV_IMPLEMENTATION_WARNINGS
  67. #warning Using I2CDEV_BUILTIN_NBWIRE implementation may adversely affect interrupt detection.
  68. #warning This I2Cdev implementation does not support:
  69. #warning - Repeated starts conditions
  70. #endif
  71. // NBWire implementation based heavily on code by Gene Knight <Gene@Telobot.com>
  72. // Originally posted on the Arduino forum at http://arduino.cc/forum/index.php/topic,70705.0.html
  73. // Originally offered to the i2cdevlib project at http://arduino.cc/forum/index.php/topic,68210.30.html
  74. TwoWire Wire;
  75. #endif
  76. #ifndef BUFFER_LENGTH
  77. // band-aid fix for platforms without Wire-defined BUFFER_LENGTH (removed from some official implementations)
  78. #define BUFFER_LENGTH 32
  79. #endif
  80. /** Default constructor.
  81. */
  82. I2Cdev::I2Cdev() {
  83. }
  84. /** Read a single bit from an 8-bit device register.
  85. * @param devAddr I2C slave device address
  86. * @param regAddr Register regAddr to read from
  87. * @param bitNum Bit position to read (0-7)
  88. * @param data Container for single bit value
  89. * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
  90. * @return Status of read operation (true = success)
  91. */
  92. int8_t I2Cdev::readBit(uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint8_t *data, uint16_t timeout) {
  93. uint8_t b;
  94. uint8_t count = readByte(devAddr, regAddr, &b, timeout);
  95. *data = b & (1 << bitNum);
  96. return count;
  97. }
  98. /** Read a single bit from a 16-bit device register.
  99. * @param devAddr I2C slave device address
  100. * @param regAddr Register regAddr to read from
  101. * @param bitNum Bit position to read (0-15)
  102. * @param data Container for single bit value
  103. * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
  104. * @return Status of read operation (true = success)
  105. */
  106. int8_t I2Cdev::readBitW(uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint16_t *data, uint16_t timeout) {
  107. uint16_t b;
  108. uint8_t count = readWord(devAddr, regAddr, &b, timeout);
  109. *data = b & (1 << bitNum);
  110. return count;
  111. }
  112. /** Read multiple bits from an 8-bit device register.
  113. * @param devAddr I2C slave device address
  114. * @param regAddr Register regAddr to read from
  115. * @param bitStart First bit position to read (0-7)
  116. * @param length Number of bits to read (not more than 8)
  117. * @param data Container for right-aligned value (i.e. '101' read from any bitStart position will equal 0x05)
  118. * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
  119. * @return Status of read operation (true = success)
  120. */
  121. int8_t I2Cdev::readBits(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint8_t *data, uint16_t timeout) {
  122. // 01101001 read byte
  123. // 76543210 bit numbers
  124. // xxx args: bitStart=4, length=3
  125. // 010 masked
  126. // -> 010 shifted
  127. uint8_t count, b;
  128. if ((count = readByte(devAddr, regAddr, &b, timeout)) != 0) {
  129. uint8_t mask = ((1 << length) - 1) << (bitStart - length + 1);
  130. b &= mask;
  131. b >>= (bitStart - length + 1);
  132. *data = b;
  133. }
  134. return count;
  135. }
  136. /** Read multiple bits from a 16-bit device register.
  137. * @param devAddr I2C slave device address
  138. * @param regAddr Register regAddr to read from
  139. * @param bitStart First bit position to read (0-15)
  140. * @param length Number of bits to read (not more than 16)
  141. * @param data Container for right-aligned value (i.e. '101' read from any bitStart position will equal 0x05)
  142. * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
  143. * @return Status of read operation (1 = success, 0 = failure, -1 = timeout)
  144. */
  145. int8_t I2Cdev::readBitsW(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint16_t *data, uint16_t timeout) {
  146. // 1101011001101001 read byte
  147. // fedcba9876543210 bit numbers
  148. // xxx args: bitStart=12, length=3
  149. // 010 masked
  150. // -> 010 shifted
  151. uint8_t count;
  152. uint16_t w;
  153. if ((count = readWord(devAddr, regAddr, &w, timeout)) != 0) {
  154. uint16_t mask = ((1 << length) - 1) << (bitStart - length + 1);
  155. w &= mask;
  156. w >>= (bitStart - length + 1);
  157. *data = w;
  158. }
  159. return count;
  160. }
  161. /** Read single byte from an 8-bit device register.
  162. * @param devAddr I2C slave device address
  163. * @param regAddr Register regAddr to read from
  164. * @param data Container for byte value read from device
  165. * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
  166. * @return Status of read operation (true = success)
  167. */
  168. int8_t I2Cdev::readByte(uint8_t devAddr, uint8_t regAddr, uint8_t *data, uint16_t timeout) {
  169. return readBytes(devAddr, regAddr, 1, data, timeout);
  170. }
  171. /** Read single word from a 16-bit device register.
  172. * @param devAddr I2C slave device address
  173. * @param regAddr Register regAddr to read from
  174. * @param data Container for word value read from device
  175. * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
  176. * @return Status of read operation (true = success)
  177. */
  178. int8_t I2Cdev::readWord(uint8_t devAddr, uint8_t regAddr, uint16_t *data, uint16_t timeout) {
  179. return readWords(devAddr, regAddr, 1, data, timeout);
  180. }
  181. /** Read multiple bytes from an 8-bit device register.
  182. * @param devAddr I2C slave device address
  183. * @param regAddr First register regAddr to read from
  184. * @param length Number of bytes to read
  185. * @param data Buffer to store read data in
  186. * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
  187. * @return Number of bytes read (-1 indicates failure)
  188. */
  189. int8_t I2Cdev::readBytes(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint8_t *data, uint16_t timeout) {
  190. #ifdef I2CDEV_SERIAL_DEBUG
  191. Serial.print("I2C (0x");
  192. Serial.print(devAddr, HEX);
  193. Serial.print(") reading ");
  194. Serial.print(length, DEC);
  195. Serial.print(" bytes from 0x");
  196. Serial.print(regAddr, HEX);
  197. Serial.print("...");
  198. #endif
  199. int8_t count = 0;
  200. uint32_t t1 = millis();
  201. #if (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_SBWIRE || I2CDEV_IMPLEMENTATION == I2CDEV_TEENSY_3X_WIRE)
  202. #if (ARDUINO < 100)
  203. // Arduino v00xx (before v1.0), Wire library
  204. // I2C/TWI subsystem uses internal buffer that breaks with large data requests
  205. // so if user requests more than BUFFER_LENGTH bytes, we have to do it in
  206. // smaller chunks instead of all at once
  207. for (uint8_t k = 0; k < length; k += min((int)length, BUFFER_LENGTH)) {
  208. Wire.beginTransmission(devAddr);
  209. Wire.send(regAddr);
  210. Wire.endTransmission();
  211. Wire.beginTransmission(devAddr);
  212. Wire.requestFrom(devAddr, (uint8_t)min(length - k, BUFFER_LENGTH));
  213. for (; Wire.available() && (timeout == 0 || millis() - t1 < timeout); count++) {
  214. data[count] = Wire.receive();
  215. #ifdef I2CDEV_SERIAL_DEBUG
  216. Serial.print(data[count], HEX);
  217. if (count + 1 < length) Serial.print(" ");
  218. #endif
  219. }
  220. Wire.endTransmission();
  221. }
  222. #elif (ARDUINO == 100)
  223. // Arduino v1.0.0, Wire library
  224. // Adds standardized write() and read() stream methods instead of send() and receive()
  225. // I2C/TWI subsystem uses internal buffer that breaks with large data requests
  226. // so if user requests more than BUFFER_LENGTH bytes, we have to do it in
  227. // smaller chunks instead of all at once
  228. for (uint8_t k = 0; k < length; k += min((int)length, BUFFER_LENGTH)) {
  229. Wire.beginTransmission(devAddr);
  230. Wire.write(regAddr);
  231. Wire.endTransmission();
  232. Wire.beginTransmission(devAddr);
  233. Wire.requestFrom(devAddr, (uint8_t)min(length - k, BUFFER_LENGTH));
  234. for (; Wire.available() && (timeout == 0 || millis() - t1 < timeout); count++) {
  235. data[count] = Wire.read();
  236. #ifdef I2CDEV_SERIAL_DEBUG
  237. Serial.print(data[count], HEX);
  238. if (count + 1 < length) Serial.print(" ");
  239. #endif
  240. }
  241. Wire.endTransmission();
  242. }
  243. #elif (ARDUINO > 100)
  244. // Arduino v1.0.1+, Wire library
  245. // Adds official support for repeated start condition, yay!
  246. // I2C/TWI subsystem uses internal buffer that breaks with large data requests
  247. // so if user requests more than BUFFER_LENGTH bytes, we have to do it in
  248. // smaller chunks instead of all at once
  249. for (uint8_t k = 0; k < length; k += min((int)length, BUFFER_LENGTH)) {
  250. Wire.beginTransmission(devAddr);
  251. Wire.write(regAddr);
  252. Wire.endTransmission();
  253. Wire.beginTransmission(devAddr);
  254. Wire.requestFrom(devAddr, (uint8_t)min(length - k, BUFFER_LENGTH));
  255. for (; Wire.available() && (timeout == 0 || millis() - t1 < timeout); count++) {
  256. data[count] = Wire.read();
  257. #ifdef I2CDEV_SERIAL_DEBUG
  258. Serial.print(data[count], HEX);
  259. if (count + 1 < length) Serial.print(" ");
  260. #endif
  261. }
  262. }
  263. #endif
  264. #elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE)
  265. // Fastwire library
  266. // no loop required for fastwire
  267. uint8_t status = Fastwire::readBuf(devAddr << 1, regAddr, data, length);
  268. if (status == 0) {
  269. count = length; // success
  270. } else {
  271. count = -1; // error
  272. }
  273. #endif
  274. // check for timeout
  275. if (timeout > 0 && millis() - t1 >= timeout && count < length) count = -1; // timeout
  276. #ifdef I2CDEV_SERIAL_DEBUG
  277. Serial.print(". Done (");
  278. Serial.print(count, DEC);
  279. Serial.println(" read).");
  280. #endif
  281. return count;
  282. }
  283. /** Read multiple words from a 16-bit device register.
  284. * @param devAddr I2C slave device address
  285. * @param regAddr First register regAddr to read from
  286. * @param length Number of words to read
  287. * @param data Buffer to store read data in
  288. * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
  289. * @return Number of words read (-1 indicates failure)
  290. */
  291. int8_t I2Cdev::readWords(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint16_t *data, uint16_t timeout) {
  292. #ifdef I2CDEV_SERIAL_DEBUG
  293. Serial.print("I2C (0x");
  294. Serial.print(devAddr, HEX);
  295. Serial.print(") reading ");
  296. Serial.print(length, DEC);
  297. Serial.print(" words from 0x");
  298. Serial.print(regAddr, HEX);
  299. Serial.print("...");
  300. #endif
  301. int8_t count = 0;
  302. uint32_t t1 = millis();
  303. #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_SBWIRE || I2CDEV_IMPLEMENTATION == I2CDEV_TEENSY_3X_WIRE
  304. #if (ARDUINO < 100)
  305. // Arduino v00xx (before v1.0), Wire library
  306. // I2C/TWI subsystem uses internal buffer that breaks with large data requests
  307. // so if user requests more than BUFFER_LENGTH bytes, we have to do it in
  308. // smaller chunks instead of all at once
  309. for (uint8_t k = 0; k < length * 2; k += min(length * 2, BUFFER_LENGTH)) {
  310. Wire.beginTransmission(devAddr);
  311. Wire.send(regAddr);
  312. Wire.endTransmission();
  313. Wire.beginTransmission(devAddr);
  314. Wire.requestFrom(devAddr, (uint8_t)(length * 2)); // length=words, this wants bytes
  315. bool msb = true; // starts with MSB, then LSB
  316. for (; Wire.available() && count < length && (timeout == 0 || millis() - t1 < timeout);) {
  317. if (msb) {
  318. // first byte is bits 15-8 (MSb=15)
  319. data[count] = Wire.receive() << 8;
  320. } else {
  321. // second byte is bits 7-0 (LSb=0)
  322. data[count] |= Wire.receive();
  323. #ifdef I2CDEV_SERIAL_DEBUG
  324. Serial.print(data[count], HEX);
  325. if (count + 1 < length) Serial.print(" ");
  326. #endif
  327. count++;
  328. }
  329. msb = !msb;
  330. }
  331. Wire.endTransmission();
  332. }
  333. #elif (ARDUINO == 100)
  334. // Arduino v1.0.0, Wire library
  335. // Adds standardized write() and read() stream methods instead of send() and receive()
  336. // I2C/TWI subsystem uses internal buffer that breaks with large data requests
  337. // so if user requests more than BUFFER_LENGTH bytes, we have to do it in
  338. // smaller chunks instead of all at once
  339. for (uint8_t k = 0; k < length * 2; k += min(length * 2, BUFFER_LENGTH)) {
  340. Wire.beginTransmission(devAddr);
  341. Wire.write(regAddr);
  342. Wire.endTransmission();
  343. Wire.beginTransmission(devAddr);
  344. Wire.requestFrom(devAddr, (uint8_t)(length * 2)); // length=words, this wants bytes
  345. bool msb = true; // starts with MSB, then LSB
  346. for (; Wire.available() && count < length && (timeout == 0 || millis() - t1 < timeout);) {
  347. if (msb) {
  348. // first byte is bits 15-8 (MSb=15)
  349. data[count] = Wire.read() << 8;
  350. } else {
  351. // second byte is bits 7-0 (LSb=0)
  352. data[count] |= Wire.read();
  353. #ifdef I2CDEV_SERIAL_DEBUG
  354. Serial.print(data[count], HEX);
  355. if (count + 1 < length) Serial.print(" ");
  356. #endif
  357. count++;
  358. }
  359. msb = !msb;
  360. }
  361. Wire.endTransmission();
  362. }
  363. #elif (ARDUINO > 100)
  364. // Arduino v1.0.1+, Wire library
  365. // Adds official support for repeated start condition, yay!
  366. // I2C/TWI subsystem uses internal buffer that breaks with large data requests
  367. // so if user requests more than BUFFER_LENGTH bytes, we have to do it in
  368. // smaller chunks instead of all at once
  369. for (uint8_t k = 0; k < length * 2; k += min(length * 2, BUFFER_LENGTH)) {
  370. Wire.beginTransmission(devAddr);
  371. Wire.write(regAddr);
  372. Wire.endTransmission();
  373. Wire.beginTransmission(devAddr);
  374. Wire.requestFrom(devAddr, (uint8_t)(length * 2)); // length=words, this wants bytes
  375. bool msb = true; // starts with MSB, then LSB
  376. for (; Wire.available() && count < length && (timeout == 0 || millis() - t1 < timeout);) {
  377. if (msb) {
  378. // first byte is bits 15-8 (MSb=15)
  379. data[count] = Wire.read() << 8;
  380. } else {
  381. // second byte is bits 7-0 (LSb=0)
  382. data[count] |= Wire.read();
  383. #ifdef I2CDEV_SERIAL_DEBUG
  384. Serial.print(data[count], HEX);
  385. if (count + 1 < length) Serial.print(" ");
  386. #endif
  387. count++;
  388. }
  389. msb = !msb;
  390. }
  391. Wire.endTransmission();
  392. }
  393. #endif
  394. #elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE)
  395. // Fastwire library
  396. // no loop required for fastwire
  397. uint8_t intermediate[(uint8_t)length*2];
  398. uint8_t status = Fastwire::readBuf(devAddr << 1, regAddr, intermediate, (uint8_t)(length * 2));
  399. if (status == 0) {
  400. count = length; // success
  401. for (uint8_t i = 0; i < length; i++) {
  402. data[i] = (intermediate[2*i] << 8) | intermediate[2*i + 1];
  403. }
  404. } else {
  405. count = -1; // error
  406. }
  407. #endif
  408. if (timeout > 0 && millis() - t1 >= timeout && count < length) count = -1; // timeout
  409. #ifdef I2CDEV_SERIAL_DEBUG
  410. Serial.print(". Done (");
  411. Serial.print(count, DEC);
  412. Serial.println(" read).");
  413. #endif
  414. return count;
  415. }
  416. /** write a single bit in an 8-bit device register.
  417. * @param devAddr I2C slave device address
  418. * @param regAddr Register regAddr to write to
  419. * @param bitNum Bit position to write (0-7)
  420. * @param value New bit value to write
  421. * @return Status of operation (true = success)
  422. */
  423. bool I2Cdev::writeBit(uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint8_t data) {
  424. uint8_t b;
  425. readByte(devAddr, regAddr, &b);
  426. b = (data != 0) ? (b | (1 << bitNum)) : (b & ~(1 << bitNum));
  427. return writeByte(devAddr, regAddr, b);
  428. }
  429. /** write a single bit in a 16-bit device register.
  430. * @param devAddr I2C slave device address
  431. * @param regAddr Register regAddr to write to
  432. * @param bitNum Bit position to write (0-15)
  433. * @param value New bit value to write
  434. * @return Status of operation (true = success)
  435. */
  436. bool I2Cdev::writeBitW(uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint16_t data) {
  437. uint16_t w;
  438. readWord(devAddr, regAddr, &w);
  439. w = (data != 0) ? (w | (1 << bitNum)) : (w & ~(1 << bitNum));
  440. return writeWord(devAddr, regAddr, w);
  441. }
  442. /** Write multiple bits in an 8-bit device register.
  443. * @param devAddr I2C slave device address
  444. * @param regAddr Register regAddr to write to
  445. * @param bitStart First bit position to write (0-7)
  446. * @param length Number of bits to write (not more than 8)
  447. * @param data Right-aligned value to write
  448. * @return Status of operation (true = success)
  449. */
  450. bool I2Cdev::writeBits(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint8_t data) {
  451. // 010 value to write
  452. // 76543210 bit numbers
  453. // xxx args: bitStart=4, length=3
  454. // 00011100 mask byte
  455. // 10101111 original value (sample)
  456. // 10100011 original & ~mask
  457. // 10101011 masked | value
  458. uint8_t b;
  459. if (readByte(devAddr, regAddr, &b) != 0) {
  460. uint8_t mask = ((1 << length) - 1) << (bitStart - length + 1);
  461. data <<= (bitStart - length + 1); // shift data into correct position
  462. data &= mask; // zero all non-important bits in data
  463. b &= ~(mask); // zero all important bits in existing byte
  464. b |= data; // combine data with existing byte
  465. return writeByte(devAddr, regAddr, b);
  466. } else {
  467. return false;
  468. }
  469. }
  470. /** Write multiple bits in a 16-bit device register.
  471. * @param devAddr I2C slave device address
  472. * @param regAddr Register regAddr to write to
  473. * @param bitStart First bit position to write (0-15)
  474. * @param length Number of bits to write (not more than 16)
  475. * @param data Right-aligned value to write
  476. * @return Status of operation (true = success)
  477. */
  478. bool I2Cdev::writeBitsW(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint16_t data) {
  479. // 010 value to write
  480. // fedcba9876543210 bit numbers
  481. // xxx args: bitStart=12, length=3
  482. // 0001110000000000 mask word
  483. // 1010111110010110 original value (sample)
  484. // 1010001110010110 original & ~mask
  485. // 1010101110010110 masked | value
  486. uint16_t w;
  487. if (readWord(devAddr, regAddr, &w) != 0) {
  488. uint16_t mask = ((1 << length) - 1) << (bitStart - length + 1);
  489. data <<= (bitStart - length + 1); // shift data into correct position
  490. data &= mask; // zero all non-important bits in data
  491. w &= ~(mask); // zero all important bits in existing word
  492. w |= data; // combine data with existing word
  493. return writeWord(devAddr, regAddr, w);
  494. } else {
  495. return false;
  496. }
  497. }
  498. /** Write single byte to an 8-bit device register.
  499. * @param devAddr I2C slave device address
  500. * @param regAddr Register address to write to
  501. * @param data New byte value to write
  502. * @return Status of operation (true = success)
  503. */
  504. bool I2Cdev::writeByte(uint8_t devAddr, uint8_t regAddr, uint8_t data) {
  505. return writeBytes(devAddr, regAddr, 1, &data);
  506. }
  507. /** Write single word to a 16-bit device register.
  508. * @param devAddr I2C slave device address
  509. * @param regAddr Register address to write to
  510. * @param data New word value to write
  511. * @return Status of operation (true = success)
  512. */
  513. bool I2Cdev::writeWord(uint8_t devAddr, uint8_t regAddr, uint16_t data) {
  514. return writeWords(devAddr, regAddr, 1, &data);
  515. }
  516. /** Write multiple bytes to an 8-bit device register.
  517. * @param devAddr I2C slave device address
  518. * @param regAddr First register address to write to
  519. * @param length Number of bytes to write
  520. * @param data Buffer to copy new data from
  521. * @return Status of operation (true = success)
  522. */
  523. bool I2Cdev::writeBytes(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint8_t* data) {
  524. #ifdef I2CDEV_SERIAL_DEBUG
  525. Serial.print("I2C (0x");
  526. Serial.print(devAddr, HEX);
  527. Serial.print(") writing ");
  528. Serial.print(length, DEC);
  529. Serial.print(" bytes to 0x");
  530. Serial.print(regAddr, HEX);
  531. Serial.print("...");
  532. #endif
  533. uint8_t status = 0;
  534. #if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
  535. Wire.beginTransmission(devAddr);
  536. Wire.send((uint8_t) regAddr); // send address
  537. #elif ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100) \
  538. || (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_SBWIRE && ARDUINO >= 100) \
  539. || I2CDEV_IMPLEMENTATION == I2CDEV_TEENSY_3X_WIRE)
  540. Wire.beginTransmission(devAddr);
  541. Wire.write((uint8_t) regAddr); // send address
  542. #elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE)
  543. Fastwire::beginTransmission(devAddr);
  544. Fastwire::write(regAddr);
  545. #endif
  546. for (uint8_t i = 0; i < length; i++) {
  547. #ifdef I2CDEV_SERIAL_DEBUG
  548. Serial.print(data[i], HEX);
  549. if (i + 1 < length) Serial.print(" ");
  550. #endif
  551. #if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
  552. Wire.send((uint8_t) data[i]);
  553. #elif ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100) \
  554. || (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_SBWIRE && ARDUINO >= 100) \
  555. || I2CDEV_IMPLEMENTATION == I2CDEV_TEENSY_3X_WIRE)
  556. Wire.write((uint8_t) data[i]);
  557. #elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE)
  558. Fastwire::write((uint8_t) data[i]);
  559. #endif
  560. }
  561. #if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
  562. Wire.endTransmission();
  563. #elif ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100) \
  564. || (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_SBWIRE && ARDUINO >= 100) \
  565. || I2CDEV_IMPLEMENTATION == I2CDEV_TEENSY_3X_WIRE)
  566. status = Wire.endTransmission();
  567. #elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE)
  568. Fastwire::stop();
  569. //status = Fastwire::endTransmission();
  570. #endif
  571. #ifdef I2CDEV_SERIAL_DEBUG
  572. Serial.println(". Done.");
  573. #endif
  574. return status == 0;
  575. }
  576. /** Write multiple words to a 16-bit device register.
  577. * @param devAddr I2C slave device address
  578. * @param regAddr First register address to write to
  579. * @param length Number of words to write
  580. * @param data Buffer to copy new data from
  581. * @return Status of operation (true = success)
  582. */
  583. bool I2Cdev::writeWords(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint16_t* data) {
  584. #ifdef I2CDEV_SERIAL_DEBUG
  585. Serial.print("I2C (0x");
  586. Serial.print(devAddr, HEX);
  587. Serial.print(") writing ");
  588. Serial.print(length, DEC);
  589. Serial.print(" words to 0x");
  590. Serial.print(regAddr, HEX);
  591. Serial.print("...");
  592. #endif
  593. uint8_t status = 0;
  594. #if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
  595. Wire.beginTransmission(devAddr);
  596. Wire.send(regAddr); // send address
  597. #elif ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100) \
  598. || (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_SBWIRE && ARDUINO >= 100) \
  599. || I2CDEV_IMPLEMENTATION == I2CDEV_TEENSY_3X_WIRE)
  600. Wire.beginTransmission(devAddr);
  601. Wire.write(regAddr); // send address
  602. #elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE)
  603. Fastwire::beginTransmission(devAddr);
  604. Fastwire::write(regAddr);
  605. #endif
  606. for (uint8_t i = 0; i < length; i++) {
  607. #ifdef I2CDEV_SERIAL_DEBUG
  608. Serial.print(data[i], HEX);
  609. if (i + 1 < length) Serial.print(" ");
  610. #endif
  611. #if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
  612. Wire.send((uint8_t)(data[i] >> 8)); // send MSB
  613. Wire.send((uint8_t)data[i]); // send LSB
  614. #elif ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100) \
  615. || (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_SBWIRE && ARDUINO >= 100) \
  616. || I2CDEV_IMPLEMENTATION == I2CDEV_TEENSY_3X_WIRE)
  617. Wire.write((uint8_t)(data[i] >> 8)); // send MSB
  618. Wire.write((uint8_t)data[i]); // send LSB
  619. #elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE)
  620. Fastwire::write((uint8_t)(data[i] >> 8)); // send MSB
  621. status = Fastwire::write((uint8_t)data[i]); // send LSB
  622. if (status != 0) break;
  623. #endif
  624. }
  625. #if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
  626. Wire.endTransmission();
  627. #elif ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100) \
  628. || (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_SBWIRE && ARDUINO >= 100) \
  629. || I2CDEV_IMPLEMENTATION == I2CDEV_TEENSY_3X_WIRE)
  630. status = Wire.endTransmission();
  631. #elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE)
  632. Fastwire::stop();
  633. //status = Fastwire::endTransmission();
  634. #endif
  635. #ifdef I2CDEV_SERIAL_DEBUG
  636. Serial.println(". Done.");
  637. #endif
  638. return status == 0;
  639. }
  640. /** Default timeout value for read operations.
  641. * Set this to 0 to disable timeout detection.
  642. */
  643. uint16_t I2Cdev::readTimeout = I2CDEV_DEFAULT_READ_TIMEOUT;
  644. #if I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
  645. // I2C library
  646. //////////////////////
  647. // Copyright(C) 2012
  648. // Francesco Ferrara
  649. // ferrara[at]libero[point]it
  650. //////////////////////
  651. /*
  652. FastWire
  653. - 0.24 added stop
  654. - 0.23 added reset
  655. This is a library to help faster programs to read I2C devices.
  656. Copyright(C) 2012 Francesco Ferrara
  657. occhiobello at gmail dot com
  658. [used by Jeff Rowberg for I2Cdevlib with permission]
  659. */
  660. boolean Fastwire::waitInt() {
  661. int l = 250;
  662. while (!(TWCR & (1 << TWINT)) && l-- > 0);
  663. return l > 0;
  664. }
  665. void Fastwire::setup(int khz, boolean pullup) {
  666. TWCR = 0;
  667. #if defined(__AVR_ATmega168__) || defined(__AVR_ATmega8__) || defined(__AVR_ATmega328P__)
  668. // activate internal pull-ups for twi (PORTC bits 4 & 5)
  669. // as per note from atmega8 manual pg167
  670. if (pullup) PORTC |= ((1 << 4) | (1 << 5));
  671. else PORTC &= ~((1 << 4) | (1 << 5));
  672. #elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__)
  673. // activate internal pull-ups for twi (PORTC bits 0 & 1)
  674. if (pullup) PORTC |= ((1 << 0) | (1 << 1));
  675. else PORTC &= ~((1 << 0) | (1 << 1));
  676. #else
  677. // activate internal pull-ups for twi (PORTD bits 0 & 1)
  678. // as per note from atmega128 manual pg204
  679. if (pullup) PORTD |= ((1 << 0) | (1 << 1));
  680. else PORTD &= ~((1 << 0) | (1 << 1));
  681. #endif
  682. TWSR = 0; // no prescaler => prescaler = 1
  683. TWBR = ((16000L / khz) - 16) / 2; // change the I2C clock rate
  684. TWCR = 1 << TWEN; // enable twi module, no interrupt
  685. }
  686. // added by Jeff Rowberg 2013-05-07:
  687. // Arduino Wire-style "beginTransmission" function
  688. // (takes 7-bit device address like the Wire method, NOT 8-bit: 0x68, not 0xD0/0xD1)
  689. byte Fastwire::beginTransmission(byte device) {
  690. byte twst, retry;
  691. retry = 2;
  692. do {
  693. TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO) | (1 << TWSTA);
  694. if (!waitInt()) return 1;
  695. twst = TWSR & 0xF8;
  696. if (twst != TW_START && twst != TW_REP_START) return 2;
  697. //Serial.print(device, HEX);
  698. //Serial.print(" ");
  699. TWDR = device << 1; // send device address without read bit (1)
  700. TWCR = (1 << TWINT) | (1 << TWEN);
  701. if (!waitInt()) return 3;
  702. twst = TWSR & 0xF8;
  703. } while (twst == TW_MT_SLA_NACK && retry-- > 0);
  704. if (twst != TW_MT_SLA_ACK) return 4;
  705. return 0;
  706. }
  707. byte Fastwire::writeBuf(byte device, byte address, byte *data, byte num) {
  708. byte twst, retry;
  709. retry = 2;
  710. do {
  711. TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO) | (1 << TWSTA);
  712. if (!waitInt()) return 1;
  713. twst = TWSR & 0xF8;
  714. if (twst != TW_START && twst != TW_REP_START) return 2;
  715. //Serial.print(device, HEX);
  716. //Serial.print(" ");
  717. TWDR = device & 0xFE; // send device address without read bit (1)
  718. TWCR = (1 << TWINT) | (1 << TWEN);
  719. if (!waitInt()) return 3;
  720. twst = TWSR & 0xF8;
  721. } while (twst == TW_MT_SLA_NACK && retry-- > 0);
  722. if (twst != TW_MT_SLA_ACK) return 4;
  723. //Serial.print(address, HEX);
  724. //Serial.print(" ");
  725. TWDR = address; // send data to the previously addressed device
  726. TWCR = (1 << TWINT) | (1 << TWEN);
  727. if (!waitInt()) return 5;
  728. twst = TWSR & 0xF8;
  729. if (twst != TW_MT_DATA_ACK) return 6;
  730. for (byte i = 0; i < num; i++) {
  731. //Serial.print(data[i], HEX);
  732. //Serial.print(" ");
  733. TWDR = data[i]; // send data to the previously addressed device
  734. TWCR = (1 << TWINT) | (1 << TWEN);
  735. if (!waitInt()) return 7;
  736. twst = TWSR & 0xF8;
  737. if (twst != TW_MT_DATA_ACK) return 8;
  738. }
  739. //Serial.print("\n");
  740. return 0;
  741. }
  742. byte Fastwire::write(byte value) {
  743. byte twst;
  744. //Serial.println(value, HEX);
  745. TWDR = value; // send data
  746. TWCR = (1 << TWINT) | (1 << TWEN);
  747. if (!waitInt()) return 1;
  748. twst = TWSR & 0xF8;
  749. if (twst != TW_MT_DATA_ACK) return 2;
  750. return 0;
  751. }
  752. byte Fastwire::readBuf(byte device, byte address, byte *data, byte num) {
  753. byte twst, retry;
  754. retry = 2;
  755. do {
  756. TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO) | (1 << TWSTA);
  757. if (!waitInt()) return 16;
  758. twst = TWSR & 0xF8;
  759. if (twst != TW_START && twst != TW_REP_START) return 17;
  760. //Serial.print(device, HEX);
  761. //Serial.print(" ");
  762. TWDR = device & 0xfe; // send device address to write
  763. TWCR = (1 << TWINT) | (1 << TWEN);
  764. if (!waitInt()) return 18;
  765. twst = TWSR & 0xF8;
  766. } while (twst == TW_MT_SLA_NACK && retry-- > 0);
  767. if (twst != TW_MT_SLA_ACK) return 19;
  768. //Serial.print(address, HEX);
  769. //Serial.print(" ");
  770. TWDR = address; // send data to the previously addressed device
  771. TWCR = (1 << TWINT) | (1 << TWEN);
  772. if (!waitInt()) return 20;
  773. twst = TWSR & 0xF8;
  774. if (twst != TW_MT_DATA_ACK) return 21;
  775. /***/
  776. retry = 2;
  777. do {
  778. TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO) | (1 << TWSTA);
  779. if (!waitInt()) return 22;
  780. twst = TWSR & 0xF8;
  781. if (twst != TW_START && twst != TW_REP_START) return 23;
  782. //Serial.print(device, HEX);
  783. //Serial.print(" ");
  784. TWDR = device | 0x01; // send device address with the read bit (1)
  785. TWCR = (1 << TWINT) | (1 << TWEN);
  786. if (!waitInt()) return 24;
  787. twst = TWSR & 0xF8;
  788. } while (twst == TW_MR_SLA_NACK && retry-- > 0);
  789. if (twst != TW_MR_SLA_ACK) return 25;
  790. for (uint8_t i = 0; i < num; i++) {
  791. if (i == num - 1)
  792. TWCR = (1 << TWINT) | (1 << TWEN);
  793. else
  794. TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWEA);
  795. if (!waitInt()) return 26;
  796. twst = TWSR & 0xF8;
  797. if (twst != TW_MR_DATA_ACK && twst != TW_MR_DATA_NACK) return twst;
  798. data[i] = TWDR;
  799. //Serial.print(data[i], HEX);
  800. //Serial.print(" ");
  801. }
  802. //Serial.print("\n");
  803. stop();
  804. return 0;
  805. }
  806. void Fastwire::reset() {
  807. TWCR = 0;
  808. }
  809. byte Fastwire::stop() {
  810. TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO);
  811. if (!waitInt()) return 1;
  812. return 0;
  813. }
  814. #endif
  815. #if I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE
  816. // NBWire implementation based heavily on code by Gene Knight <Gene@Telobot.com>
  817. // Originally posted on the Arduino forum at http://arduino.cc/forum/index.php/topic,70705.0.html
  818. // Originally offered to the i2cdevlib project at http://arduino.cc/forum/index.php/topic,68210.30.html
  819. /*
  820. call this version 1.0
  821. Offhand, the only funky part that I can think of is in nbrequestFrom, where the buffer
  822. length and index are set *before* the data is actually read. The problem is that these
  823. are variables local to the TwoWire object, and by the time we actually have read the
  824. data, and know what the length actually is, we have no simple access to the object's
  825. variables. The actual bytes read *is* given to the callback function, though.
  826. The ISR code for a slave receiver is commented out. I don't have that setup, and can't
  827. verify it at this time. Save it for 2.0!
  828. The handling of the read and write processes here is much like in the demo sketch code:
  829. the process is broken down into sequential functions, where each registers the next as a
  830. callback, essentially.
  831. For example, for the Read process, twi_read00 just returns if TWI is not yet in a
  832. ready state. When there's another interrupt, and the interface *is* ready, then it
  833. sets up the read, starts it, and registers twi_read01 as the function to call after
  834. the *next* interrupt. twi_read01, then, just returns if the interface is still in a
  835. "reading" state. When the reading is done, it copies the information to the buffer,
  836. cleans up, and calls the user-requested callback function with the actual number of
  837. bytes read.
  838. The writing is similar.
  839. Questions, comments and problems can go to Gene@Telobot.com.
  840. Thumbs Up!
  841. Gene Knight
  842. */
  843. uint8_t TwoWire::rxBuffer[NBWIRE_BUFFER_LENGTH];
  844. uint8_t TwoWire::rxBufferIndex = 0;
  845. uint8_t TwoWire::rxBufferLength = 0;
  846. uint8_t TwoWire::txAddress = 0;
  847. uint8_t TwoWire::txBuffer[NBWIRE_BUFFER_LENGTH];
  848. uint8_t TwoWire::txBufferIndex = 0;
  849. uint8_t TwoWire::txBufferLength = 0;
  850. //uint8_t TwoWire::transmitting = 0;
  851. void (*TwoWire::user_onRequest)(void);
  852. void (*TwoWire::user_onReceive)(int);
  853. static volatile uint8_t twi_transmitting;
  854. static volatile uint8_t twi_state;
  855. static uint8_t twi_slarw;
  856. static volatile uint8_t twi_error;
  857. static uint8_t twi_masterBuffer[TWI_BUFFER_LENGTH];
  858. static volatile uint8_t twi_masterBufferIndex;
  859. static uint8_t twi_masterBufferLength;
  860. static uint8_t twi_rxBuffer[TWI_BUFFER_LENGTH];
  861. static volatile uint8_t twi_rxBufferIndex;
  862. //static volatile uint8_t twi_Interrupt_Continue_Command;
  863. static volatile uint8_t twi_Return_Value;
  864. static volatile uint8_t twi_Done;
  865. void (*twi_cbendTransmissionDone)(int);
  866. void (*twi_cbreadFromDone)(int);
  867. void twi_init() {
  868. // initialize state
  869. twi_state = TWI_READY;
  870. // activate internal pull-ups for twi
  871. // as per note from atmega8 manual pg167
  872. sbi(PORTC, 4);
  873. sbi(PORTC, 5);
  874. // initialize twi prescaler and bit rate
  875. cbi(TWSR, TWPS0); // TWI Status Register - Prescaler bits
  876. cbi(TWSR, TWPS1);
  877. /* twi bit rate formula from atmega128 manual pg 204
  878. SCL Frequency = CPU Clock Frequency / (16 + (2 * TWBR))
  879. note: TWBR should be 10 or higher for master mode
  880. It is 72 for a 16mhz Wiring board with 100kHz TWI */
  881. TWBR = ((CPU_FREQ / TWI_FREQ) - 16) / 2; // bitrate register
  882. // enable twi module, acks, and twi interrupt
  883. TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA);
  884. /* TWEN - TWI Enable Bit
  885. TWIE - TWI Interrupt Enable
  886. TWEA - TWI Enable Acknowledge Bit
  887. TWINT - TWI Interrupt Flag
  888. TWSTA - TWI Start Condition
  889. */
  890. }
  891. typedef struct {
  892. uint8_t address;
  893. uint8_t* data;
  894. uint8_t length;
  895. uint8_t wait;
  896. uint8_t i;
  897. } twi_Write_Vars;
  898. twi_Write_Vars *ptwv = 0;
  899. static void (*fNextInterruptFunction)(void) = 0;
  900. void twi_Finish(byte bRetVal) {
  901. if (ptwv) {
  902. free(ptwv);
  903. ptwv = 0;
  904. }
  905. twi_Done = 0xFF;
  906. twi_Return_Value = bRetVal;
  907. fNextInterruptFunction = 0;
  908. }
  909. uint8_t twii_WaitForDone(uint16_t timeout) {
  910. uint32_t endMillis = millis() + timeout;
  911. while (!twi_Done && (timeout == 0 || millis() < endMillis)) continue;
  912. return twi_Return_Value;
  913. }
  914. void twii_SetState(uint8_t ucState) {
  915. twi_state = ucState;
  916. }
  917. void twii_SetError(uint8_t ucError) {
  918. twi_error = ucError ;
  919. }
  920. void twii_InitBuffer(uint8_t ucPos, uint8_t ucLength) {
  921. twi_masterBufferIndex = 0;
  922. twi_masterBufferLength = ucLength;
  923. }
  924. void twii_CopyToBuf(uint8_t* pData, uint8_t ucLength) {
  925. uint8_t i;
  926. for (i = 0; i < ucLength; ++i) {
  927. twi_masterBuffer[i] = pData[i];
  928. }
  929. }
  930. void twii_CopyFromBuf(uint8_t *pData, uint8_t ucLength) {
  931. uint8_t i;
  932. for (i = 0; i < ucLength; ++i) {
  933. pData[i] = twi_masterBuffer[i];
  934. }
  935. }
  936. void twii_SetSlaRW(uint8_t ucSlaRW) {
  937. twi_slarw = ucSlaRW;
  938. }
  939. void twii_SetStart() {
  940. TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTA);
  941. }
  942. void twi_write01() {
  943. if (TWI_MTX == twi_state) return; // blocking test
  944. twi_transmitting = 0 ;
  945. if (twi_error == 0xFF)
  946. twi_Finish (0); // success
  947. else if (twi_error == TW_MT_SLA_NACK)
  948. twi_Finish (2); // error: address send, nack received
  949. else if (twi_error == TW_MT_DATA_NACK)
  950. twi_Finish (3); // error: data send, nack received
  951. else
  952. twi_Finish (4); // other twi error
  953. if (twi_cbendTransmissionDone) return twi_cbendTransmissionDone(twi_Return_Value);
  954. return;
  955. }
  956. void twi_write00() {
  957. if (TWI_READY != twi_state) return; // blocking test
  958. if (TWI_BUFFER_LENGTH < ptwv -> length) {
  959. twi_Finish(1); // end write with error 1
  960. return;
  961. }
  962. twi_Done = 0x00; // show as working
  963. twii_SetState(TWI_MTX); // to transmitting
  964. twii_SetError(0xFF); // to No Error
  965. twii_InitBuffer(0, ptwv -> length); // pointer and length
  966. twii_CopyToBuf(ptwv -> data, ptwv -> length); // get the data
  967. twii_SetSlaRW((ptwv -> address << 1) | TW_WRITE); // write command
  968. twii_SetStart(); // start the cycle
  969. fNextInterruptFunction = twi_write01; // next routine
  970. return twi_write01();
  971. }
  972. void twi_writeTo(uint8_t address, uint8_t* data, uint8_t length, uint8_t wait) {
  973. uint8_t i;
  974. ptwv = (twi_Write_Vars *)malloc(sizeof(twi_Write_Vars));
  975. ptwv -> address = address;
  976. ptwv -> data = data;
  977. ptwv -> length = length;
  978. ptwv -> wait = wait;
  979. fNextInterruptFunction = twi_write00;
  980. return twi_write00();
  981. }
  982. void twi_read01() {
  983. if (TWI_MRX == twi_state) return; // blocking test
  984. if (twi_masterBufferIndex < ptwv -> length) ptwv -> length = twi_masterBufferIndex;
  985. twii_CopyFromBuf(ptwv -> data, ptwv -> length);
  986. twi_Finish(ptwv -> length);
  987. if (twi_cbreadFromDone) return twi_cbreadFromDone(twi_Return_Value);
  988. return;
  989. }
  990. void twi_read00() {
  991. if (TWI_READY != twi_state) return; // blocking test
  992. if (TWI_BUFFER_LENGTH < ptwv -> length) twi_Finish(0); // error return
  993. twi_Done = 0x00; // show as working
  994. twii_SetState(TWI_MRX); // reading
  995. twii_SetError(0xFF); // reset error
  996. twii_InitBuffer(0, ptwv -> length - 1); // init to one less than length
  997. twii_SetSlaRW((ptwv -> address << 1) | TW_READ); // read command
  998. twii_SetStart(); // start cycle
  999. fNextInterruptFunction = twi_read01;
  1000. return twi_read01();
  1001. }
  1002. void twi_readFrom(uint8_t address, uint8_t* data, uint8_t length) {
  1003. uint8_t i;
  1004. ptwv = (twi_Write_Vars *)malloc(sizeof(twi_Write_Vars));
  1005. ptwv -> address = address;
  1006. ptwv -> data = data;
  1007. ptwv -> length = length;
  1008. fNextInterruptFunction = twi_read00;
  1009. return twi_read00();
  1010. }
  1011. void twi_reply(uint8_t ack) {
  1012. // transmit master read ready signal, with or without ack
  1013. if (ack){
  1014. TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWINT) | _BV(TWEA);
  1015. } else {
  1016. TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWINT);
  1017. }
  1018. }
  1019. void twi_stop(void) {
  1020. // send stop condition
  1021. TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTO);
  1022. // wait for stop condition to be exectued on bus
  1023. // TWINT is not set after a stop condition!
  1024. while (TWCR & _BV(TWSTO)) {
  1025. continue;
  1026. }
  1027. // update twi state
  1028. twi_state = TWI_READY;
  1029. }
  1030. void twi_releaseBus(void) {
  1031. // release bus
  1032. TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT);
  1033. // update twi state
  1034. twi_state = TWI_READY;
  1035. }
  1036. SIGNAL(TWI_vect) {
  1037. switch (TW_STATUS) {
  1038. // All Master
  1039. case TW_START: // sent start condition
  1040. case TW_REP_START: // sent repeated start condition
  1041. // copy device address and r/w bit to output register and ack
  1042. TWDR = twi_slarw;
  1043. twi_reply(1);
  1044. break;
  1045. // Master Transmitter
  1046. case TW_MT_SLA_ACK: // slave receiver acked address
  1047. case TW_MT_DATA_ACK: // slave receiver acked data
  1048. // if there is data to send, send it, otherwise stop
  1049. if (twi_masterBufferIndex < twi_masterBufferLength) {
  1050. // copy data to output register and ack
  1051. TWDR = twi_masterBuffer[twi_masterBufferIndex++];
  1052. twi_reply(1);
  1053. } else {
  1054. twi_stop();
  1055. }
  1056. break;
  1057. case TW_MT_SLA_NACK: // address sent, nack received
  1058. twi_error = TW_MT_SLA_NACK;
  1059. twi_stop();
  1060. break;
  1061. case TW_MT_DATA_NACK: // data sent, nack received
  1062. twi_error = TW_MT_DATA_NACK;
  1063. twi_stop();
  1064. break;
  1065. case TW_MT_ARB_LOST: // lost bus arbitration
  1066. twi_error = TW_MT_ARB_LOST;
  1067. twi_releaseBus();
  1068. break;
  1069. // Master Receiver
  1070. case TW_MR_DATA_ACK: // data received, ack sent
  1071. // put byte into buffer
  1072. twi_masterBuffer[twi_masterBufferIndex++] = TWDR;
  1073. case TW_MR_SLA_ACK: // address sent, ack received
  1074. // ack if more bytes are expected, otherwise nack
  1075. if (twi_masterBufferIndex < twi_masterBufferLength) {
  1076. twi_reply(1);
  1077. } else {
  1078. twi_reply(0);
  1079. }
  1080. break;
  1081. case TW_MR_DATA_NACK: // data received, nack sent
  1082. // put final byte into buffer
  1083. twi_masterBuffer[twi_masterBufferIndex++] = TWDR;
  1084. case TW_MR_SLA_NACK: // address sent, nack received
  1085. twi_stop();
  1086. break;
  1087. // TW_MR_ARB_LOST handled by TW_MT_ARB_LOST case
  1088. // Slave Receiver (NOT IMPLEMENTED YET)
  1089. /*
  1090. case TW_SR_SLA_ACK: // addressed, returned ack
  1091. case TW_SR_GCALL_ACK: // addressed generally, returned ack
  1092. case TW_SR_ARB_LOST_SLA_ACK: // lost arbitration, returned ack
  1093. case TW_SR_ARB_LOST_GCALL_ACK: // lost arbitration, returned ack
  1094. // enter slave receiver mode
  1095. twi_state = TWI_SRX;
  1096. // indicate that rx buffer can be overwritten and ack
  1097. twi_rxBufferIndex = 0;
  1098. twi_reply(1);
  1099. break;
  1100. case TW_SR_DATA_ACK: // data received, returned ack
  1101. case TW_SR_GCALL_DATA_ACK: // data received generally, returned ack
  1102. // if there is still room in the rx buffer
  1103. if (twi_rxBufferIndex < TWI_BUFFER_LENGTH) {
  1104. // put byte in buffer and ack
  1105. twi_rxBuffer[twi_rxBufferIndex++] = TWDR;
  1106. twi_reply(1);
  1107. } else {
  1108. // otherwise nack
  1109. twi_reply(0);
  1110. }
  1111. break;
  1112. case TW_SR_STOP: // stop or repeated start condition received
  1113. // put a null char after data if there's room
  1114. if (twi_rxBufferIndex < TWI_BUFFER_LENGTH) {
  1115. twi_rxBuffer[twi_rxBufferIndex] = 0;
  1116. }
  1117. // sends ack and stops interface for clock stretching
  1118. twi_stop();
  1119. // callback to user defined callback
  1120. twi_onSlaveReceive(twi_rxBuffer, twi_rxBufferIndex);
  1121. // since we submit rx buffer to "wire" library, we can reset it
  1122. twi_rxBufferIndex = 0;
  1123. // ack future responses and leave slave receiver state
  1124. twi_releaseBus();
  1125. break;
  1126. case TW_SR_DATA_NACK: // data received, returned nack
  1127. case TW_SR_GCALL_DATA_NACK: // data received generally, returned nack
  1128. // nack back at master
  1129. twi_reply(0);
  1130. break;
  1131. // Slave Transmitter
  1132. case TW_ST_SLA_ACK: // addressed, returned ack
  1133. case TW_ST_ARB_LOST_SLA_ACK: // arbitration lost, returned ack
  1134. // enter slave transmitter mode
  1135. twi_state = TWI_STX;
  1136. // ready the tx buffer index for iteration
  1137. twi_txBufferIndex = 0;
  1138. // set tx buffer length to be zero, to verify if user changes it
  1139. twi_txBufferLength = 0;
  1140. // request for txBuffer to be filled and length to be set
  1141. // note: user must call twi_transmit(bytes, length) to do this
  1142. twi_onSlaveTransmit();
  1143. // if they didn't change buffer & length, initialize it
  1144. if (0 == twi_txBufferLength) {
  1145. twi_txBufferLength = 1;
  1146. twi_txBuffer[0] = 0x00;
  1147. }
  1148. // transmit first byte from buffer, fall through
  1149. case TW_ST_DATA_ACK: // byte sent, ack returned
  1150. // copy data to output register
  1151. TWDR = twi_txBuffer[twi_txBufferIndex++];
  1152. // if there is more to send, ack, otherwise nack
  1153. if (twi_txBufferIndex < twi_txBufferLength) {
  1154. twi_reply(1);
  1155. } else {
  1156. twi_reply(0);
  1157. }
  1158. break;
  1159. case TW_ST_DATA_NACK: // received nack, we are done
  1160. case TW_ST_LAST_DATA: // received ack, but we are done already!
  1161. // ack future responses
  1162. twi_reply(1);
  1163. // leave slave receiver state
  1164. twi_state = TWI_READY;
  1165. break;
  1166. */
  1167. // all
  1168. case TW_NO_INFO: // no state information
  1169. break;
  1170. case TW_BUS_ERROR: // bus error, illegal stop/start
  1171. twi_error = TW_BUS_ERROR;
  1172. twi_stop();
  1173. break;
  1174. }
  1175. if (fNextInterruptFunction) return fNextInterruptFunction();
  1176. }
  1177. TwoWire::TwoWire() { }
  1178. void TwoWire::begin(void) {
  1179. rxBufferIndex = 0;
  1180. rxBufferLength = 0;
  1181. txBufferIndex = 0;
  1182. txBufferLength = 0;
  1183. twi_init();
  1184. }
  1185. void TwoWire::beginTransmission(uint8_t address) {
  1186. //beginTransmission((uint8_t)address);
  1187. // indicate that we are transmitting
  1188. twi_transmitting = 1;
  1189. // set address of targeted slave
  1190. txAddress = address;
  1191. // reset tx buffer iterator vars
  1192. txBufferIndex = 0;
  1193. txBufferLength = 0;
  1194. }
  1195. uint8_t TwoWire::endTransmission(uint16_t timeout) {
  1196. // transmit buffer (blocking)
  1197. //int8_t ret =
  1198. twi_cbendTransmissionDone = NULL;
  1199. twi_writeTo(txAddress, txBuffer, txBufferLength, 1);
  1200. int8_t ret = twii_WaitForDone(timeout);
  1201. // reset tx buffer iterator vars
  1202. txBufferIndex = 0;
  1203. txBufferLength = 0;
  1204. // indicate that we are done transmitting
  1205. // twi_transmitting = 0;
  1206. return ret;
  1207. }
  1208. void TwoWire::nbendTransmission(void (*function)(int)) {
  1209. twi_cbendTransmissionDone = function;
  1210. twi_writeTo(txAddress, txBuffer, txBufferLength, 1);
  1211. return;
  1212. }
  1213. void TwoWire::send(uint8_t data) {
  1214. if (twi_transmitting) {
  1215. // in master transmitter mode
  1216. // don't bother if buffer is full
  1217. if (txBufferLength >= NBWIRE_BUFFER_LENGTH) {
  1218. return;
  1219. }
  1220. // put byte in tx buffer
  1221. txBuffer[txBufferIndex] = data;
  1222. ++txBufferIndex;
  1223. // update amount in buffer
  1224. txBufferLength = txBufferIndex;
  1225. } else {
  1226. // in slave send mode
  1227. // reply to master
  1228. //twi_transmit(&data, 1);
  1229. }
  1230. }
  1231. uint8_t TwoWire::receive(void) {
  1232. // default to returning null char
  1233. // for people using with char strings
  1234. uint8_t value = 0;
  1235. // get each successive byte on each call
  1236. if (rxBufferIndex < rxBufferLength) {
  1237. value = rxBuffer[rxBufferIndex];
  1238. ++rxBufferIndex;
  1239. }
  1240. return value;
  1241. }
  1242. uint8_t TwoWire::requestFrom(uint8_t address, int quantity, uint16_t timeout) {
  1243. // clamp to buffer length
  1244. if (quantity > NBWIRE_BUFFER_LENGTH) {
  1245. quantity = NBWIRE_BUFFER_LENGTH;
  1246. }
  1247. // perform blocking read into buffer
  1248. twi_cbreadFromDone = NULL;
  1249. twi_readFrom(address, rxBuffer, quantity);
  1250. uint8_t read = twii_WaitForDone(timeout);
  1251. // set rx buffer iterator vars
  1252. rxBufferIndex = 0;
  1253. rxBufferLength = read;
  1254. return read;
  1255. }
  1256. void TwoWire::nbrequestFrom(uint8_t address, int quantity, void (*function)(int)) {
  1257. // clamp to buffer length
  1258. if (quantity > NBWIRE_BUFFER_LENGTH) {
  1259. quantity = NBWIRE_BUFFER_LENGTH;
  1260. }
  1261. // perform blocking read into buffer
  1262. twi_cbreadFromDone = function;
  1263. twi_readFrom(address, rxBuffer, quantity);
  1264. //uint8_t read = twii_WaitForDone();
  1265. // set rx buffer iterator vars
  1266. //rxBufferIndex = 0;
  1267. //rxBufferLength = read;
  1268. rxBufferIndex = 0;
  1269. rxBufferLength = quantity; // this is a hack
  1270. return; //read;
  1271. }
  1272. uint8_t TwoWire::available(void) {
  1273. return rxBufferLength - rxBufferIndex;
  1274. }
  1275. #endif