单片机教程网

电脑版
提示:原网页已由神马搜索转码, 内容由www.51hei.com提供.
查看:5728|回复:4
打印上一主题下一主题

Arduino i2c库文件下载

[复制链接]
跳转到指定楼层
楼主
ID:442463发表于 2018-12-8 23:38|只看该作者|只看大图回帖奖励


所有资料51hei提供下载:
I2Cdev.7z(11.12 KB, 下载次数: 197)

源程序如下:
  1. // I2Cdev library collection - Main I2C device class
  2. // Abstracts bit and byte I2C R/W functions into a convenient class
  3. // 6/9/2012 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

  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.0.1+ 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.0.1+ 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.0.1+ 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. /** Default constructor.
  77. */
  78. I2Cdev::I2Cdev() {
  79. }

  80. /** Read a single bit from an 8-bit device register.
  81. * @param devAddr I2C slave device address
  82. * @param regAddr Register regAddr to read from
  83. * @param bitNum Bit position to read (0-7)
  84. * @param data Container for single bit value
  85. * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
  86. * @return Status of read operation (true = success)
  87. */
  88. int8_t I2Cdev::readBit(uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint8_t *data, uint16_t timeout) {
  89.    uint8_t b;
  90.    uint8_t count = readByte(devAddr, regAddr,& b, timeout);
  91.    *data = b& (1<< bitNum);
  92.    return count;
  93. }

  94. /** Read a single bit from a 16-bit device register.
  95. * @param devAddr I2C slave device address
  96. * @param regAddr Register regAddr to read from
  97. * @param bitNum Bit position to read (0-15)
  98. * @param data Container for single bit value
  99. * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
  100. * @return Status of read operation (true = success)
  101. */
  102. int8_t I2Cdev::readBitW(uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint16_t *data, uint16_t timeout) {
  103.    uint16_t b;
  104.    uint8_t count = readWord(devAddr, regAddr,& b, timeout);
  105.    *data = b& (1<< bitNum);
  106.    return count;
  107. }

  108. /** Read multiple bits from an 8-bit device register.
  109. * @param devAddr I2C slave device address
  110. * @param regAddr Register regAddr to read from
  111. * @param bitStart First bit position to read (0-7)
  112. * @param length Number of bits to read (not more than 8)
  113. * @param data Container for right-aligned value (i.e. '101' read from any bitStart position will equal 0x05)
  114. * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
  115. * @return Status of read operation (true = success)
  116. */
  117. int8_t I2Cdev::readBits(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint8_t *data, uint16_t timeout) {
  118.    // 01101001 read byte
  119.    // 76543210 bit numbers
  120.    //   xxx   args: bitStart=4, length=3
  121.    //   010   masked
  122.    //   -> 010 shifted
  123.    uint8_t count, b;
  124.    if ((count = readByte(devAddr, regAddr,& b, timeout)) != 0) {
  125.        uint8_t mask = ((1<< length) - 1)<< (bitStart - length + 1);
  126.        b& = mask;
  127.        b >>= (bitStart - length + 1);
  128.        *data = b;
  129.    }
  130.    return count;
  131. }

  132. /** Read multiple bits from a 16-bit device register.
  133. * @param devAddr I2C slave device address
  134. * @param regAddr Register regAddr to read from
  135. * @param bitStart First bit position to read (0-15)
  136. * @param length Number of bits to read (not more than 16)
  137. * @param data Container for right-aligned value (i.e. '101' read from any bitStart position will equal 0x05)
  138. * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
  139. * @return Status of read operation (1 = success, 0 = failure, -1 = timeout)
  140. */
  141. int8_t I2Cdev::readBitsW(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint16_t *data, uint16_t timeout) {
  142.    // 1101011001101001 read byte
  143.    // fedcba9876543210 bit numbers
  144.    //   xxx         args: bitStart=12, length=3
  145.    //   010         masked
  146.    //         -> 010 shifted
  147.    uint8_t count;
  148.    uint16_t w;
  149.    if ((count = readWord(devAddr, regAddr,& w, timeout)) != 0) {
  150.        uint16_t mask = ((1<< length) - 1)<< (bitStart - length + 1);
  151.        w& = mask;
  152.        w >>= (bitStart - length + 1);
  153.        *data = w;
  154.    }
  155.    return count;
  156. }

  157. /** Read single byte from an 8-bit device register.
  158. * @param devAddr I2C slave device address
  159. * @param regAddr Register regAddr to read from
  160. * @param data Container for byte value read from device
  161. * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
  162. * @return Status of read operation (true = success)
  163. */
  164. int8_t I2Cdev::readByte(uint8_t devAddr, uint8_t regAddr, uint8_t *data, uint16_t timeout) {
  165.    return readBytes(devAddr, regAddr, 1, data, timeout);
  166. }

  167. /** Read single word from a 16-bit device register.
  168. * @param devAddr I2C slave device address
  169. * @param regAddr Register regAddr to read from
  170. * @param data Container for word value read from device
  171. * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
  172. * @return Status of read operation (true = success)
  173. */
  174. int8_t I2Cdev::readWord(uint8_t devAddr, uint8_t regAddr, uint16_t *data, uint16_t timeout) {
  175.    return readWords(devAddr, regAddr, 1, data, timeout);
  176. }

  177. /** Read multiple bytes from an 8-bit device register.
  178. * @param devAddr I2C slave device address
  179. * @param regAddr First register regAddr to read from
  180. * @param length Number of bytes to read
  181. * @param data Buffer to store read data in
  182. * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
  183. * @return Number of bytes read (-1 indicates failure)
  184. */
  185. int8_t I2Cdev::readBytes(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint8_t *data, uint16_t timeout) {
  186.    #ifdef I2CDEV_SERIAL_DEBUG
  187.        Serial.print("I2C (0x");
  188.        Serial.print(devAddr, HEX);
  189.        Serial.print(") reading ");
  190.        Serial.print(length, DEC);
  191.        Serial.print(" bytes from 0x");
  192.        Serial.print(regAddr, HEX);
  193.        Serial.print("...");
  194.    #endif

  195.    int8_t count = 0;
  196.    uint32_t t1 = millis();

  197.    #if (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE)

  198.        #if (ARDUINO< 100)
  199.          // Arduino v00xx (before v1.0), Wire library

  200.          // I2C/TWI subsystem uses internal buffer that breaks with large data requests
  201.          // so if user requests more than BUFFER_LENGTH bytes, we have to do it in
  202.          // smaller chunks instead of all at once
  203.          for (uint8_t k = 0; k< length; k += min(length, BUFFER_LENGTH)) {
  204.            Wire.beginTransmission(devAddr);
  205.            Wire.send(regAddr);
  206.            Wire.endTransmission();
  207.            Wire.beginTransmission(devAddr);
  208.            Wire.requestFrom(devAddr, (uint8_t)min(length - k, BUFFER_LENGTH));

  209.            for (; Wire.available()&& (timeout == 0 || millis() - t1< timeout); count++) {
  210.                data[count] = Wire.receive();
  211.                #ifdef I2CDEV_SERIAL_DEBUG
  212.                  Serial.print(data[count], HEX);
  213.                  if (count + 1< length) Serial.print(" ");
  214.                #endif
  215.            }

  216.            Wire.endTransmission();
  217.          }
  218.        #elif (ARDUINO == 100)
  219.          // Arduino v1.0.0, Wire library
  220.          // Adds standardized write() and read() stream methods instead of send() and receive()

  221.          // I2C/TWI subsystem uses internal buffer that breaks with large data requests
  222.          // so if user requests more than BUFFER_LENGTH bytes, we have to do it in
  223.          // smaller chunks instead of all at once
  224.          for (uint8_t k = 0; k< length; k += min(length, BUFFER_LENGTH)) {
  225.            Wire.beginTransmission(devAddr);
  226.            Wire.write(regAddr);
  227.            Wire.endTransmission();
  228.            Wire.beginTransmission(devAddr);
  229.            Wire.requestFrom(devAddr, (uint8_t)min(length - k, BUFFER_LENGTH));
  230.       
  231.            for (; Wire.available()&& (timeout == 0 || millis() - t1< timeout); count++) {
  232.                data[count] = Wire.read();
  233.                #ifdef I2CDEV_SERIAL_DEBUG
  234.                  Serial.print(data[count], HEX);
  235.                  if (count + 1< length) Serial.print(" ");
  236.                #endif
  237.            }
  238.       
  239.            Wire.endTransmission();
  240.          }
  241.        #elif (ARDUINO > 100)
  242.          // Arduino v1.0.1+, Wire library
  243.          // Adds official support for repeated start condition, yay!

  244.          // I2C/TWI subsystem uses internal buffer that breaks with large data requests
  245.          // so if user requests more than BUFFER_LENGTH bytes, we have to do it in
  246.          // smaller chunks instead of all at once
  247.          for (uint8_t k = 0; k< length; k += min(length, BUFFER_LENGTH)) {
  248.            Wire.beginTransmission(devAddr);
  249.            Wire.write(regAddr);
  250.            Wire.endTransmission();
  251.            Wire.beginTransmission(devAddr);
  252.            Wire.requestFrom(devAddr, (uint8_t)min(length - k, BUFFER_LENGTH));
  253.       
  254.            for (; Wire.available()&& (timeout == 0 || millis() - t1< timeout); count++) {
  255.                data[count] = Wire.read();
  256.                #ifdef I2CDEV_SERIAL_DEBUG
  257.                  Serial.print(data[count], HEX);
  258.                  if (count + 1< length) Serial.print(" ");
  259.                #endif
  260.            }
  261.          }
  262.        #endif

  263.    #elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE)

  264.        // Fastwire library
  265.        // no loop required for fastwire
  266.        uint8_t status = Fastwire::readBuf(devAddr<< 1, regAddr, data, length);
  267.        if (status == 0) {
  268.          count = length; // success
  269.        } else {
  270.          count = -1; // error
  271.        }

  272.    #endif

  273.    // check for timeout
  274.    if (timeout > 0&& millis() - t1 >= timeout&& count< length) count = -1; // timeout

  275.    #ifdef I2CDEV_SERIAL_DEBUG
  276.        Serial.print(". Done (");
  277.        Serial.print(count, DEC);
  278.        Serial.println(" read).");
  279.    #endif

  280.    return count;
  281. }

  282. /** Read multiple words from a 16-bit device register.
  283. * @param devAddr I2C slave device address
  284. * @param regAddr First register regAddr to read from
  285. * @param length Number of words to read
  286. * @param data Buffer to store read data in
  287. * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
  288. * @return Number of words read (-1 indicates failure)
  289. */
  290. int8_t I2Cdev::readWords(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint16_t *data, uint16_t timeout) {
  291.    #ifdef I2CDEV_SERIAL_DEBUG
  292.        Serial.print("I2C (0x");
  293.        Serial.print(devAddr, HEX);
  294.        Serial.print(") reading ");
  295.        Serial.print(length, DEC);
  296.        Serial.print(" words from 0x");
  297.        Serial.print(regAddr, HEX);
  298.        Serial.print("...");
  299.    #endif

  300.    int8_t count = 0;
  301.    uint32_t t1 = millis();

  302.    #if (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE)

  303.        #if (ARDUINO< 100)
  304.          // Arduino v00xx (before v1.0), Wire library

  305.          // I2C/TWI subsystem uses internal buffer that breaks with large data requests
  306.          // so if user requests more than BUFFER_LENGTH bytes, we have to do it in
  307.          // smaller chunks instead of all at once
  308.          for (uint8_t k = 0; k< length * 2; k += min(length * 2, BUFFER_LENGTH)) {
  309.            Wire.beginTransmission(devAddr);
  310.            Wire.send(regAddr);
  311.            Wire.endTransmission();
  312.            Wire.beginTransmission(devAddr);
  313.            Wire.requestFrom(devAddr, (uint8_t)(length * 2)); // length=words, this wants bytes
  314.   
  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.   
  337.          // I2C/TWI subsystem uses internal buffer that breaks with large data requests
  338.          // so if user requests more than BUFFER_LENGTH bytes, we have to do it in
  339.          // smaller chunks instead of all at once
  340.          for (uint8_t k = 0; k< length * 2; k += min(length * 2, BUFFER_LENGTH)) {
  341.            Wire.beginTransmission(devAddr);
  342.            Wire.write(regAddr);
  343.            Wire.endTransmission();
  344.            Wire.beginTransmission(devAddr);
  345.            Wire.requestFrom(devAddr, (uint8_t)(length * 2)); // length=words, this wants bytes
  346.   
  347.            bool msb = true; // starts with MSB, then LSB
  348.            for (; Wire.available()&& count< length&& (timeout == 0 || millis() - t1< timeout);) {
  349.                if (msb) {
  350.                  // first byte is bits 15-8 (MSb=15)
  351.                  data[count] = Wire.read()<< 8;
  352.                } else {
  353.                  // second byte is bits 7-0 (LSb=0)
  354.                  data[count] |= Wire.read();
  355.                  #ifdef I2CDEV_SERIAL_DEBUG
  356.                    Serial.print(data[count], HEX);
  357.                    if (count + 1< length) Serial.print(" ");
  358.                  #endif
  359.                  count++;
  360.                }
  361.                msb = !msb;
  362.            }
  363.       
  364.            Wire.endTransmission();
  365.          }
  366.        #elif (ARDUINO > 100)
  367.          // Arduino v1.0.1+, Wire library
  368.          // Adds official support for repeated start condition, yay!

  369.          // I2C/TWI subsystem uses internal buffer that breaks with large data requests
  370.          // so if user requests more than BUFFER_LENGTH bytes, we have to do it in
  371.          // smaller chunks instead of all at once
  372.          for (uint8_t k = 0; k< length * 2; k += min(length * 2, BUFFER_LENGTH)) {
  373.            Wire.beginTransmission(devAddr);
  374.            Wire.write(regAddr);
  375.            Wire.endTransmission();
  376.            Wire.beginTransmission(devAddr);
  377.            Wire.requestFrom(devAddr, (uint8_t)(length * 2)); // length=words, this wants bytes
  378.       
  379.            bool msb = true; // starts with MSB, then LSB
  380.            for (; Wire.available()&& count< length&& (timeout == 0 || millis() - t1< timeout);) {
  381.                if (msb) {
  382.                  // first byte is bits 15-8 (MSb=15)
  383.                  data[count] = Wire.read()<< 8;
  384.                } else {
  385.                  // second byte is bits 7-0 (LSb=0)
  386.                  data[count] |= Wire.read();
  387.                  #ifdef I2CDEV_SERIAL_DEBUG
  388.                    Serial.print(data[count], HEX);
  389.                    if (count + 1< length) Serial.print(" ");
  390.                  #endif
  391.                  count++;
  392.                }
  393.                msb = !msb;
  394.            }
  395.       
  396.            Wire.endTransmission();
  397.          }
  398.        #endif

  399.    #elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE)

  400.        // Fastwire library
  401.        // no loop required for fastwire
  402.        uint16_t intermediate[(uint8_t)length];
  403.        uint8_t status = Fastwire::readBuf(devAddr<< 1, regAddr, (uint8_t *)intermediate, (uint8_t)(length * 2));
  404.        if (status == 0) {
  405.          count = length; // success
  406.          for (uint8_t i = 0; i< length; i++) {
  407.            data[i] = (intermediate[2*i]<< 8) | intermediate[2*i + 1];
  408.          }
  409.        } else {
  410.          count = -1; // error
  411.        }

  412.    #endif

  413.    if (timeout > 0&& millis() - t1 >= timeout&& count< length) count = -1; // timeout

  414.    #ifdef I2CDEV_SERIAL_DEBUG
  415.        Serial.print(". Done (");
  416.        Serial.print(count, DEC);
  417.        Serial.println(" read).");
  418.    #endif
  419.   
  420.    return count;
  421. }

  422. /** write a single bit in an 8-bit device register.
  423. * @param devAddr I2C slave device address
  424. * @param regAddr Register regAddr to write to
  425. * @param bitNum Bit position to write (0-7)
  426. * @param value New bit value to write
  427. * @return Status of operation (true = success)
  428. */
  429. bool I2Cdev::writeBit(uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint8_t data) {
  430.    uint8_t b;
  431.    readByte(devAddr, regAddr,& b);
  432.    b = (data != 0) ? (b | (1<< bitNum)) : (b& ~(1<< bitNum));
  433.    return writeByte(devAddr, regAddr, b);
  434. }

  435. /** write a single bit in a 16-bit device register.
  436. * @param devAddr I2C slave device address
  437. * @param regAddr Register regAddr to write to
  438. * @param bitNum Bit position to write (0-15)
  439. * @param value New bit value to write
  440. * @return Status of operation (true = success)
  441. */
  442. bool I2Cdev::writeBitW(uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint16_t data) {
  443.    uint16_t w;
  444.    readWord(devAddr, regAddr,& w);
  445.    w = (data != 0) ? (w | (1<< bitNum)) : (w& ~(1<< bitNum));
  446.    return writeWord(devAddr, regAddr, w);
  447. }

  448. /** Write multiple bits in an 8-bit device register.
  449. * @param devAddr I2C slave device address
  450. * @param regAddr Register regAddr to write to
  451. * @param bitStart First bit position to write (0-7)
  452. * @param length Number of bits to write (not more than 8)
  453. * @param data Right-aligned value to write
  454. * @return Status of operation (true = success)
  455. */
  456. bool I2Cdev::writeBits(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint8_t data) {
  457.    //     010 value to write
  458.    // 76543210 bit numbers
  459.    //   xxx   args: bitStart=4, length=3
  460.    // 00011100 mask byte
  461.    // 10101111 original value (sample)
  462.    // 10100011 original& ~mask
  463.    // 10101011 masked | value
  464.    uint8_t b;
  465.    if (readByte(devAddr, regAddr,& b) != 0) {
  466.        uint8_t mask = ((1<< length) - 1)<< (bitStart - length + 1);
  467.        data<< = (bitStart - length + 1); // shift data into correct position
  468.        data& = mask; // zero all non-important bits in data
  469.        b& = ~(mask); // zero all important bits in existing byte
  470.        b |= data; // combine data with existing byte
  471.        return writeByte(devAddr, regAddr, b);
  472.    } else {
  473.        return false;
  474.    }
  475. }

  476. /** Write multiple bits in a 16-bit device register.
  477. * @param devAddr I2C slave device address
  478. * @param regAddr Register regAddr to write to
  479. * @param bitStart First bit position to write (0-15)
  480. * @param length Number of bits to write (not more than 16)
  481. * @param data Right-aligned value to write
  482. * @return Status of operation (true = success)
  483. */
  484. bool I2Cdev::writeBitsW(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint16_t data) {
  485.    //           010 value to write
  486.    // fedcba9876543210 bit numbers
  487.    //   xxx         args: bitStart=12, length=3
  488.    // 0001110000000000 mask word
  489.    // 1010111110010110 original value (sample)
  490.    // 1010001110010110 original& ~mask
  491.    // 1010101110010110 masked | value
  492.    uint16_t w;
  493.    if (readWord(devAddr, regAddr,& w) != 0) {
  494.        uint16_t mask = ((1<< length) - 1)<< (bitStart - length + 1);
  495.        data<< = (bitStart - length + 1); // shift data into correct position
  496.        data& = mask; // zero all non-important bits in data
  497.        w& = ~(mask); // zero all important bits in existing word
  498.        w |= data; // combine data with existing word
  499.        return writeWord(devAddr, regAddr, w);
  500.    } else {
  501.        return false;
  502.    }
  503. }

  504. /** Write single byte to an 8-bit device register.
  505. * @param devAddr I2C slave device address
  506. * @param regAddr Register address to write to
  507. * @param data New byte value to write
  508. * @return Status of operation (true = success)
  509. */
  510. bool I2Cdev::writeByte(uint8_t devAddr, uint8_t regAddr, uint8_t data) {
  511.    return writeBytes(devAddr, regAddr, 1,& data);
  512. }

  513. /** Write single word to a 16-bit device register.
  514. * @param devAddr I2C slave device address
  515. * @param regAddr Register address to write to
  516. * @param data New word value to write
  517. * @return Status of operation (true = success)
  518. */
  519. bool I2Cdev::writeWord(uint8_t devAddr, uint8_t regAddr, uint16_t data) {
  520.    return writeWords(devAddr, regAddr, 1,& data);
  521. }

  522. /** Write multiple bytes to an 8-bit device register.
  523. * @param devAddr I2C slave device address
  524. * @param regAddr First register address to write to
  525. * @param length Number of bytes to write
  526. * @param data Buffer to copy new data from
  527. * @return Status of operation (true = success)
  528. */
  529. bool I2Cdev::writeBytes(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint8_t* data) {
  530.    #ifdef I2CDEV_SERIAL_DEBUG
  531.        Serial.print("I2C (0x");
  532.        Serial.print(devAddr, HEX);
  533.        Serial.print(") writing ");
  534.        Serial.print(length, DEC);
  535.        Serial.print(" bytes to 0x");
  536.        Serial.print(regAddr, HEX);
  537.        Serial.print("...");
  538.    #endif
  539.    uint8_t status = 0;
  540.    #if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE&& ARDUINO< 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
  541.        Wire.beginTransmission(devAddr);
  542.        Wire.send((uint8_t) regAddr); // send address
  543.    #elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE&& ARDUINO >= 100)
  544.        Wire.beginTransmission(devAddr);
  545.        Wire.write((uint8_t) regAddr); // send address
  546.    #elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE)
  547.        Fastwire::beginTransmission(devAddr);
  548.        Fastwire::write(regAddr);
  549.    #endif
  550.    for (uint8_t i = 0; i< length; i++) {
  551.        #ifdef I2CDEV_SERIAL_DEBUG
  552.          Serial.print(data[i], HEX);
  553.          if (i + 1< length) Serial.print(" ");
  554.        #endif
  555.        #if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE&& ARDUINO< 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
  556.          Wire.send((uint8_t) data[i]);
  557.        #elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE&& ARDUINO >= 100)
  558.          Wire.write((uint8_t) data[i]);
  559.        #elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE)
  560.          Fastwire::write((uint8_t) data[i]);
  561.        #endif
  562.    }
  563.    #if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE&& ARDUINO< 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
  564.        Wire.endTransmission();
  565.    #elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE&& ARDUINO >= 100)
  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.        Wire.beginTransmission(devAddr);
  599.        Wire.write(regAddr); // send address
  600.    #elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE)
  601.        Fastwire::beginTransmission(devAddr);
  602.        Fastwire::write(regAddr);
  603.    #endif
  604.    for (uint8_t i = 0; i< length * 2; i++) {
  605.        #ifdef I2CDEV_SERIAL_DEBUG
  606.          Serial.print(data[i], HEX);
  607.          if (i + 1< length) Serial.print(" ");
  608.        #endif
  609.        #if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE&& ARDUINO< 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
  610.          Wire.send((uint8_t)(data[i] >> 8));     // send MSB
  611.          Wire.send((uint8_t)data[i++]);       // send LSB
  612.        #elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE&& ARDUINO >= 100)
  613.          Wire.write((uint8_t)(data[i] >> 8));   // send MSB
  614.          Wire.write((uint8_t)data[i++]);       // send LSB
  615.        #elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE)
  616.          Fastwire::write((uint8_t)(data[i] >> 8));     // send MSB
  617.          status = Fastwire::write((uint8_t)data[i++]);   // send LSB
  618.          if (status != 0) break;
  619.        #endif
  620.    }
  621.    #if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE&& ARDUINO< 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
  622.        Wire.endTransmission();
  623.    #elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE&& ARDUINO >= 100)
  624.        status = Wire.endTransmission();
  625.    #elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE)
  626.        Fastwire::stop();
  627.        //status = Fastwire::endTransmission();
  628.    #endif
  629.    #ifdef I2CDEV_SERIAL_DEBUG
  630.        Serial.println(". Done.");
  631.    #endif
  632.    return status == 0;
  633. }

  634. /** Default timeout value for read operations.
  635. * Set this to 0 to disable timeout detection.
  636. */
  637. uint16_t I2Cdev::readTimeout = I2CDEV_DEFAULT_READ_TIMEOUT;

  638. #if I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
  639.    // I2C library
  640.    //////////////////////
  641.    // Copyright(C) 2012
  642.    // Francesco Ferrara
  643.    // ferrara[at]libero[point]it
  644.    //////////////////////

  645.    /*
  646.    FastWire
  647.    - 0.24 added stop
  648.    - 0.23 added reset

  649.      This is a library to help faster programs to read I2C devices.
  650.      Copyright(C) 2012 Francesco Ferrara
  651.      occhiobello at gmail dot com
  652.      [used by Jeff Rowberg for I2Cdevlib with permission]
  653.      */

  654.    boolean Fastwire::waitInt() {
  655.        int l = 250;
  656.        while (!(TWCR& (1<< TWINT))&& l-- > 0);
  657.        return l > 0;
  658.    }

  659.    void Fastwire::setup(int khz, boolean pullup) {
  660.        TWCR = 0;
  661.        #if defined(__AVR_ATmega168__) || defined(__AVR_ATmega8__) || defined(__AVR_ATmega328P__)
  662.          // activate internal pull-ups for twi (PORTC bits 4& 5)
  663.          // as per note from atmega8 manual pg167
  664.          if (pullup) PORTC |= ((1<< 4) | (1<< 5));
  665.          else       PORTC& = ~((1<< 4) | (1<< 5));
  666.        #elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__)
  667.          // activate internal pull-ups for twi (PORTC bits 0& 1)
  668.          if (pullup) PORTC |= ((1<< 0) | (1<< 1));
  669.          else       PORTC& = ~((1<< 0) | (1<< 1));
  670.        #else
  671.          // activate internal pull-ups for twi (PORTD bits 0& 1)
  672.          // as per note from atmega128 manual pg204
  673.          if (pullup) PORTD |= ((1<< 0) | (1<< 1));
  674.          else       PORTD& = ~((1<< 0) | (1<< 1));
  675.        #endif

  676.        TWSR = 0; // no prescaler => prescaler = 1
  677.        TWBR = ((16000L / khz) - 16) / 2; // change the I2C clock rate
  678.        TWCR = 1<< TWEN; // enable twi module, no interrupt
  679.    }

  680.    // added by Jeff Rowberg 2013-05-07:
  681.    // Arduino Wire-style "beginTransmission" function
  682.    // (takes 7-bit device address like the Wire method, NOT 8-bit: 0x68, not 0xD0/0xD1)
  683.    byte Fastwire::beginTransmission(byte device) {
  684.        byte twst, retry;
  685.        retry = 2;
  686.        do {
  687.          TWCR = (1<< TWINT) | (1<< TWEN) | (1<< TWSTO) | (1<< TWSTA);
  688.          if (!waitInt()) return 1;
  689.          twst = TWSR& 0xF8;
  690.          if (twst != TW_START&& twst != TW_REP_START) return 2;

  691.          //Serial.print(device, HEX);
  692.          //Serial.print(" ");
  693.          TWDR = device<< 1; // send device address without read bit (1)
  694.          TWCR = (1<< TWINT) | (1<< TWEN);
  695.          if (!waitInt()) return 3;
  696.          twst = TWSR& 0xF8;
  697.        } while (twst == TW_MT_SLA_NACK&& retry-- > 0);
  698.        if (twst != TW_MT_SLA_ACK) return 4;
  699.        return 0;
  700.    }

  701.    byte Fastwire::writeBuf(byte device, byte address, byte *data, byte num) {
  702.        byte twst, retry;

  703.        retry = 2;
  704.        do {
  705.          TWCR = (1<< TWINT) | (1<< TWEN) | (1<< TWSTO) | (1<< TWSTA);
  706.          if (!waitInt()) return 1;
  707.          twst = TWSR& 0xF8;
  708.          if (twst != TW_START&& twst != TW_REP_START) return 2;

  709.          //Serial.print(device, HEX);
  710.          //Serial.print(" ");
  711.          TWDR = device& 0xFE; // send device address without read bit (1)
  712.          TWCR = (1<< TWINT) | (1<< TWEN);
  713.          if (!waitInt()) return 3;
  714.          twst = TWSR& 0xF8;
  715.        } while (twst == TW_MT_SLA_NACK&& retry-- > 0);
  716.        if (twst != TW_MT_SLA_ACK) return 4;

  717.        //Serial.print(address, HEX);
  718.        //Serial.print(" ");
  719.        TWDR = address; // send data to the previously addressed device
  720.        TWCR = (1<< TWINT) | (1<< TWEN);
  721.        if (!waitInt()) return 5;
  722.        twst = TWSR& 0xF8;
  723.        if (twst != TW_MT_DATA_ACK) return 6;

  724.        for (byte i = 0; i< num; i++) {
  725.          //Serial.print(data[i], HEX);
  726.          //Serial.print(" ");
  727.          TWDR = data[i]; // send data to the previously addressed device
  728.          TWCR = (1<< TWINT) | (1<< TWEN);
  729.          if (!waitInt()) return 7;
  730.          twst = TWSR& 0xF8;
  731.          if (twst != TW_MT_DATA_ACK) return 8;
  732.        }
  733.        //Serial.print("\n");

  734.        return 0;
  735.    }

  736.    byte Fastwire::write(byte value) {
  737.        byte twst;
  738.        //Serial.println(value, HEX);
  739.        TWDR = value; // send data
  740.        TWCR = (1<< TWINT) | (1<< TWEN);
  741.        if (!waitInt()) return 1;
  742.        twst = TWSR& 0xF8;
  743.        if (twst != TW_MT_DATA_ACK) return 2;
  744.        return 0;
  745.    }

  746.    byte Fastwire::readBuf(byte device, byte address, byte *data, byte num) {
  747.        byte twst, retry;

  748.        retry = 2;
  749.        do {
  750.          TWCR = (1<< TWINT) | (1<< TWEN) | (1<< TWSTO) | (1<< TWSTA);
  751.          if (!waitInt()) return 16;
  752.          twst = TWSR& 0xF8;
  753.          if (twst != TW_START&& twst != TW_REP_START) return 17;

  754.          //Serial.print(device, HEX);
  755.          //Serial.print(" ");
  756.          TWDR = device& 0xfe; // send device address to write
  757.          TWCR = (1<< TWINT) | (1<< TWEN);
  758.          if (!waitInt()) return 18;
  759.          twst = TWSR& 0xF8;
  760.        } while (twst == TW_MT_SLA_NACK&& retry-- > 0);
  761.        if (twst != TW_MT_SLA_ACK) return 19;

  762.        //Serial.print(address, HEX);
  763.        //Serial.print(" ");
  764.        TWDR = address; // send data to the previously addressed device
  765.        TWCR = (1<< TWINT) | (1<< TWEN);
  766.        if (!waitInt()) return 20;
  767.        twst = TWSR& 0xF8;
  768.        if (twst != TW_MT_DATA_ACK) return 21;

  769.        /***/

  770.        retry = 2;
  771.        do {
  772.          TWCR = (1<< TWINT) | (1<< TWEN) | (1<< TWSTO) | (1<< TWSTA);
  773.          if (!waitInt()) return 22;
  774.          twst = TWSR& 0xF8;
  775.          if (twst != TW_START&& twst != TW_REP_START) return 23;

  776.          //Serial.print(device, HEX);
  777.          //Serial.print(" ");
  778.          TWDR = device | 0x01; // send device address with the read bit (1)
  779.          TWCR = (1<< TWINT) | (1<< TWEN);
  780.          if (!waitInt()) return 24;
  781.          twst = TWSR& 0xF8;
  782.        } while (twst == TW_MR_SLA_NACK&& retry-- > 0);
  783.        if (twst != TW_MR_SLA_ACK) return 25;

  784.        for (uint8_t i = 0; i< num; i++) {
  785.          if (i == num - 1)
  786.            TWCR = (1<< TWINT) | (1<< TWEN);
  787.          else
  788.            TWCR = (1<< TWINT) | (1<< TWEN) | (1<< TWEA);
  789.          if (!waitInt()) return 26;
  790.          twst = TWSR& 0xF8;
  791.          if (twst != TW_MR_DATA_ACK&& twst != TW_MR_DATA_NACK) return twst;
  792.          data[i] = TWDR;
  793.          //Serial.print(data[i], HEX);
  794.          //Serial.print(" ");
  795.        }
  796.        //Serial.print("\n");
  797.        stop();

  798.        return 0;
  799.    }

  800.    void Fastwire::reset() {
  801.        TWCR = 0;
  802.    }

  803.    byte Fastwire::stop() {
  804.        TWCR = (1<< TWINT) | (1<< TWEN) | (1<< TWSTO);
  805.        if (!waitInt()) return 1;
  806.        return 0;
  807.    }
  808. #endif

  809. #if I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE
  810.    // NBWire implementation based heavily on code by Gene Knight< Gene@Telobot.com>
  811.    // Originally posted on the Arduino forum at http://arduino.cc/forum/index.php/topic,70705.0.html
  812.    // Originally offered to the i2cdevlib project at http://arduino.cc/forum/index.php/topic,68210.30.html

  813.    /*
  814.    call this version 1.0
  815.   
  816.    Offhand, the only funky part that I can think of is in nbrequestFrom, where the buffer
  817.    length and index are set *before* the data is actually read. The problem is that these
  818.    are variables local to the TwoWire object, and by the time we actually have read the
  819.    data, and know what the length actually is, we have no simple access to the object's
  820.    variables. The actual bytes read *is* given to the callback function, though.
  821.   
  822.    The ISR code for a slave receiver is commented out. I don't have that setup, and can't
  823.    verify it at this time. Save it for 2.0!
  824.   
  825.    The handling of the read and write processes here is much like in the demo sketch code:
  826.    the process is broken down into sequential functions, where each registers the next as a
  827.    callback, essentially.
  828.   
  829.    For example, for the Read process, twi_read00 just returns if TWI is not yet in a
  830.    ready state. When there's another interrupt, and the interface *is* ready, then it
  831.    sets up the read, starts it, and registers twi_read01 as the function to call after
  832.    the *next* interrupt. twi_read01, then, just returns if the interface is still in a
  833.    "reading" state. When the reading is done, it copies the information to the buffer,
  834.    cleans up, and calls the user-requested callback function with the actual number of
  835.    bytes read.
  836.   
  837.    The writing is similar.
  838.   
  839.    Questions, comments and problems can go to Gene@Telobot.com.
  840.   
  841.    Thumbs Up!
  842.    Gene Knight
  843.   
  844.    */
  845.   
  846.    uint8_t TwoWire::rxBuffer[NBWIRE_BUFFER_LENGTH];
  847.    uint8_t TwoWire::rxBufferIndex = 0;
  848.    uint8_t TwoWire::rxBufferLength = 0;
  849.   
  850.    uint8_t TwoWire::txAddress = 0;
  851.    uint8_t TwoWire::txBuffer[NBWIRE_BUFFER_LENGTH];
  852.    uint8_t TwoWire::txBufferIndex = 0;
  853.    uint8_t TwoWire::txBufferLength = 0;
  854.   
  855.    //uint8_t TwoWire::transmitting = 0;
  856.    void (*TwoWire::user_onRequest)(void);
  857.    void (*TwoWire::user_onReceive)(int);
  858.   
  859.    static volatile uint8_t twi_transmitting;
  860.    static volatile uint8_t twi_state;
  861.    static uint8_t twi_slarw;
  862.    static volatile uint8_t twi_error;
  863.    static uint8_t twi_masterBuffer[TWI_BUFFER_LENGTH];
  864.    static volatile uint8_t twi_masterBufferIndex;
  865.    static uint8_t twi_masterBufferLength;
  866.    static uint8_t twi_rxBuffer[TWI_BUFFER_LENGTH];
  867.    static volatile uint8_t twi_rxBufferIndex;
  868.    //static volatile uint8_t twi_Interrupt_Continue_Command;
  869.    static volatile uint8_t twi_Return_Value;
  870.    static volatile uint8_t twi_Done;
  871.    void (*twi_cbendTransmissionDone)(int);
  872.    void (*twi_cbreadFromDone)(int);
  873.   
  874.    void twi_init() {
  875.        // initialize state
  876.        twi_state = TWI_READY;

  877.        // activate internal pull-ups for twi
  878.        // as per note from atmega8 manual pg167
  879.        sbi(PORTC, 4);
  880.        sbi(PORTC, 5);

  881.        // initialize twi prescaler and bit rate
  882.        cbi(TWSR, TWPS0); // TWI Status Register - Prescaler bits
  883.        cbi(TWSR, TWPS1);

  884.        /* twi bit rate formula from atmega128 manual pg 204
  885.        SCL Frequency = CPU Clock Frequency / (16 + (2 * TWBR))
  886.        note: TWBR should be 10 or higher for master mode
  887.        It is 72 for a 16mhz Wiring board with 100kHz TWI */

  888.        TWBR = ((CPU_FREQ / TWI_FREQ) - 16) / 2; // bitrate register
  889.        // enable twi module, acks, and twi interrupt

  890.        TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA);

  891.        /* TWEN - TWI Enable Bit
  892.        TWIE - TWI Interrupt Enable
  893.        TWEA - TWI Enable Acknowledge Bit
  894.        TWINT - TWI Interrupt Flag
  895.        TWSTA - TWI Start Condition
  896.        */
  897.    }
  898.   
  899.    typedef struct {
  900.        uint8_t address;
  901.        uint8_t* data;
  902.        uint8_t length;
  903.        uint8_t wait;
  904.        uint8_t i;
  905.    } twi_Write_Vars;

  906.    twi_Write_Vars *ptwv = 0;
  907.    static void (*fNextInterruptFunction)(void) = 0;

  908.    void twi_Finish(byte bRetVal) {
  909.        if (ptwv) {
  910.          free(ptwv);
  911.          ptwv = 0;
  912.        }
  913.        twi_Done = 0xFF;
  914.        twi_Return_Value = bRetVal;
  915.        fNextInterruptFunction = 0;
  916.    }
  917.   
  918.    uint8_t twii_WaitForDone(uint16_t timeout) {
  919.        uint32_t endMillis = millis() + timeout;
  920.        while (!twi_Done&& (timeout == 0 || millis()< endMillis)) continue;
  921.        return twi_Return_Value;
  922.    }
  923.   
  924.    void twii_SetState(uint8_t ucState) {
  925.        twi_state = ucState;
  926.    }

  927.    void twii_SetError(uint8_t ucError) {
  928.        twi_error = ucError ;
  929.    }

  930.    void twii_InitBuffer(uint8_t ucPos, uint8_t ucLength) {
  931.        twi_masterBufferIndex = 0;
  932.        twi_masterBufferLength = ucLength;
  933.    }

  934.    void twii_CopyToBuf(uint8_t* pData, uint8_t ucLength) {
  935.        uint8_t i;
  936.        for (i = 0; i< ucLength; ++i) {
  937.          twi_masterBuffer[i] = pData[i];
  938.        }
  939.    }

  940.    void twii_CopyFromBuf(uint8_t *pData, uint8_t ucLength) {
  941.        uint8_t i;
  942.        for (i = 0; i< ucLength; ++i) {
  943.          pData[i] = twi_masterBuffer[i];
  944.        }
  945.    }

  946.    void twii_SetSlaRW(uint8_t ucSlaRW) {
  947.        twi_slarw = ucSlaRW;
  948.    }

  949.    void twii_SetStart() {
  950.        TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTA);
  951.    }

  952.    void twi_write01() {
  953.        if (TWI_MTX == twi_state) return; // blocking test
  954.        twi_transmitting = 0 ;
  955.        if (twi_error == 0xFF)
  956.          twi_Finish (0);   // success
  957.        else if (twi_error == TW_MT_SLA_NACK)
  958.          twi_Finish (2);   // error: address send, nack received
  959.        else if (twi_error == TW_MT_DATA_NACK)
  960.          twi_Finish (3);   // error: data send, nack received
  961.        else
  962.          twi_Finish (4);   // other twi error
  963.        if (twi_cbendTransmissionDone) return twi_cbendTransmissionDone(twi_Return_Value);
  964.        return;
  965.    }
  966.   
  967.   
  968.    void twi_write00() {
  969.        if (TWI_READY != twi_state) return; // blocking test
  970.        if (TWI_BUFFER_LENGTH< ptwv -> length) {
  971.          twi_Finish(1); // end write with error 1
  972.          return;
  973.        }
  974.        twi_Done = 0x00; // show as working
  975.        twii_SetState(TWI_MTX); // to transmitting
  976.        twii_SetError(0xFF); // to No Error
  977.        twii_InitBuffer(0, ptwv -> length); // pointer and length
  978.        twii_CopyToBuf(ptwv -> data, ptwv -> length); // get the data
  979.        twii_SetSlaRW((ptwv -> address<< 1) | TW_WRITE); // write command
  980.        twii_SetStart(); // start the cycle
  981.        fNextInterruptFunction = twi_write01; // next routine
  982.        return twi_write01();
  983.    }
  984.   
  985.    void twi_writeTo(uint8_t address, uint8_t* data, uint8_t length, uint8_t wait) {
  986.        uint8_t i;
  987.        ptwv = (twi_Write_Vars *)malloc(sizeof(twi_Write_Vars));
  988.        ptwv -> address = address;
  989.        ptwv -> data = data;
  990.        ptwv -> length = length;
  991.        ptwv -> wait = wait;
  992.        fNextInterruptFunction = twi_write00;
  993.        return twi_write00();
  994.    }

  995.    void twi_read01() {
  996.        if (TWI_MRX == twi_state) return; // blocking test
  997.        if (twi_masterBufferIndex< ptwv -> length) ptwv -> length = twi_masterBufferIndex;
  998.        twii_CopyFromBuf(ptwv -> data, ptwv -> length);
  999.        twi_Finish(ptwv -> length);
  1000.        if (twi_cbreadFromDone) return twi_cbreadFromDone(twi_Return_Value);
  1001.        return;
  1002.    }
  1003.   
  1004.    void twi_read00() {
  1005.        if (TWI_READY != twi_state) return; // blocking test
  1006.        if (TWI_BUFFER_LENGTH< ptwv -> length) twi_Finish(0); // error return
  1007.        twi_Done = 0x00; // show as working
  1008.        twii_SetState(TWI_MRX); // reading
  1009.        twii_SetError(0xFF); // reset error
  1010.        twii_InitBuffer(0, ptwv -> length - 1); // init to one less than length
  1011.        twii_SetSlaRW((ptwv -> address<< 1) | TW_READ); // read command
  1012.        twii_SetStart(); // start cycle
  1013.        fNextInterruptFunction = twi_read01;
  1014.        return twi_read01();
  1015.    }

  1016.    void twi_readFrom(uint8_t address, uint8_t* data, uint8_t length) {
  1017.        uint8_t i;

  1018.        ptwv = (twi_Write_Vars *)malloc(sizeof(twi_Write_Vars));
  1019.        ptwv -> address = address;
  1020.        ptwv -> data = data;
  1021.        ptwv -> length = length;
  1022.        fNextInterruptFunction = twi_read00;
  1023.        return twi_read00();
  1024.    }

  1025.    void twi_reply(uint8_t ack) {
  1026.        // transmit master read ready signal, with or without ack
  1027.        if (ack){
  1028.          TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWINT) | _BV(TWEA);
  1029.        } else {
  1030.          TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWINT);
  1031.        }
  1032.    }
  1033.   
  1034.    void twi_stop(void) {
  1035.        // send stop condition
  1036.        TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTO);
  1037.   
  1038.        // wait for stop condition to be exectued on bus
  1039.        // TWINT is not set after a stop condition!
  1040.        while (TWCR& _BV(TWSTO)) {
  1041.          continue;
  1042.        }
  1043.   
  1044.        // update twi state
  1045.        twi_state = TWI_READY;
  1046.    }

  1047.    void twi_releaseBus(void) {
  1048.        // release bus
  1049.        TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT);
  1050.   
  1051.        // update twi state
  1052.        twi_state = TWI_READY;
  1053.    }
  1054.   
  1055.    SIGNAL(TWI_vect) {
  1056.        switch (TW_STATUS) {
  1057.          // All Master
  1058.          case TW_START:     // sent start condition
  1059.          case TW_REP_START: // sent repeated start condition
  1060.            // copy device address and r/w bit to output register and ack
  1061.            TWDR = twi_slarw;
  1062.            twi_reply(1);
  1063.            break;
  1064.   
  1065.          // Master Transmitter
  1066.          case TW_MT_SLA_ACK:  // slave receiver acked address
  1067.          case TW_MT_DATA_ACK: // slave receiver acked data
  1068.            // if there is data to send, send it, otherwise stop
  1069.            if (twi_masterBufferIndex< twi_masterBufferLength) {
  1070.                // copy data to output register and ack
  1071.                TWDR = twi_masterBuffer[twi_masterBufferIndex++];
  1072.                twi_reply(1);
  1073.            } else {
  1074.                twi_stop();
  1075.            }
  1076.            break;

  1077.          case TW_MT_SLA_NACK:  // address sent, nack received
  1078.            twi_error = TW_MT_SLA_NACK;
  1079.            twi_stop();
  1080.            break;

  1081.          case TW_MT_DATA_NACK: // data sent, nack received
  1082.            twi_error = TW_MT_DATA_NACK;
  1083.            twi_stop();
  1084.            break;

  1085.          case TW_MT_ARB_LOST: // lost bus arbitration
  1086.            twi_error = TW_MT_ARB_LOST;
  1087.            twi_releaseBus();
  1088.            break;
  1089.   
  1090.          // Master Receiver
  1091.          case TW_MR_DATA_ACK: // data received, ack sent
  1092.            // put byte into buffer
  1093.            twi_masterBuffer[twi_masterBufferIndex++] = TWDR;

  1094.          case TW_MR_SLA_ACK:  // address sent, ack received
  1095.            // ack if more bytes are expected, otherwise nack
  1096.            if (twi_masterBufferIndex< twi_masterBufferLength) {
  1097.                twi_reply(1);
  1098.            } else {
  1099.                twi_reply(0);
  1100.            }
  1101.            break;

  1102.          case TW_MR_DATA_NACK: // data received, nack sent
  1103.            // put final byte into buffer
  1104.            twi_masterBuffer[twi_masterBufferIndex++] = TWDR;

  1105.          case TW_MR_SLA_NACK: // address sent, nack received
  1106.            twi_stop();
  1107.            break;

  1108.        // TW_MR_ARB_LOST handled by TW_MT_ARB_LOST case

  1109.        // Slave Receiver (NOT IMPLEMENTED YET)
  1110.        /*
  1111.          case TW_SR_SLA_ACK:   // addressed, returned ack
  1112.          case TW_SR_GCALL_ACK: // addressed generally, returned ack
  1113.          case TW_SR_ARB_LOST_SLA_ACK:   // lost arbitration, returned ack
  1114.          case TW_SR_ARB_LOST_GCALL_ACK: // lost arbitration, returned ack
  1115.            // enter slave receiver mode
  1116.            twi_state = TWI_SRX;

  1117.            // indicate that rx buffer can be overwritten and ack
  1118.            twi_rxBufferIndex = 0;
  1119.            twi_reply(1);
  1120.            break;

  1121.          case TW_SR_DATA_ACK:     // data received, returned ack
  1122.          case TW_SR_GCALL_DATA_ACK: // data received generally, returned ack
  1123.            // if there is still room in the rx buffer
  1124.            if (twi_rxBufferIndex< TWI_BUFFER_LENGTH) {
  1125.                // put byte in buffer and ack
  1126.                twi_rxBuffer[twi_rxBufferIndex++] = TWDR;
  1127.                twi_reply(1);
  1128.            } else {
  1129.                // otherwise nack
  1130.                twi_reply(0);
  1131.            }
  1132.            break;

  1133.          case TW_SR_STOP: // stop or repeated start condition received
  1134.            // put a null char after data if there's room
  1135.            if (twi_rxBufferIndex< TWI_BUFFER_LENGTH) {
  1136.                twi_rxBuffer[twi_rxBufferIndex] = 0;
  1137.            }

  1138.            // sends ack and stops interface for clock stretching
  1139.            twi_stop();

  1140.            // callback to user defined callback
  1141.            twi_onSlaveReceive(twi_rxBuffer, twi_rxBufferIndex);

  1142.            // since we submit rx buffer to "wire" library, we can reset it
  1143.            twi_rxBufferIndex = 0;

  1144.            // ack future responses and leave slave receiver state
  1145.            twi_releaseBus();
  1146.            break;

  1147.          case TW_SR_DATA_NACK:     // data received, returned nack
  1148.          case TW_SR_GCALL_DATA_NACK: // data received generally, returned nack
  1149.            // nack back at master
  1150.            twi_reply(0);
  1151.            break;

  1152.          // Slave Transmitter
  1153.          case TW_ST_SLA_ACK:       // addressed, returned ack
  1154.          case TW_ST_ARB_LOST_SLA_ACK: // arbitration lost, returned ack
  1155.            // enter slave transmitter mode
  1156.            twi_state = TWI_STX;

  1157.            // ready the tx buffer index for iteration
  1158.            twi_txBufferIndex = 0;

  1159.            // set tx buffer length to be zero, to verify if user changes it
  1160.            twi_txBufferLength = 0;

  1161.            // request for txBuffer to be filled and length to be set
  1162.            // note: user must call twi_transmit(bytes, length) to do this
  1163.            twi_onSlaveTransmit();

  1164.            // if they didn't change buffer& length, initialize it
  1165.            if (0 == twi_txBufferLength) {
  1166.                twi_txBufferLength = 1;
  1167.                twi_txBuffer[0] = 0x00;
  1168.            }
  1169.           
  1170.            // transmit first byte from buffer, fall through

  1171.          case TW_ST_DATA_ACK: // byte sent, ack returned
  1172.            // copy data to output register
  1173.            TWDR = twi_txBuffer[twi_txBufferIndex++];

  1174.            // if there is more to send, ack, otherwise nack
  1175.            if (twi_txBufferIndex< twi_txBufferLength) {
  1176.                twi_reply(1);
  1177.            } else {
  1178.                twi_reply(0);
  1179.            }
  1180.            break;

  1181.          case TW_ST_DATA_NACK: // received nack, we are done
  1182.          case TW_ST_LAST_DATA: // received ack, but we are done already!
  1183.            // ack future responses
  1184.            twi_reply(1);
  1185.            // leave slave receiver state
  1186.            twi_state = TWI_READY;
  1187.            break;
  1188.          */

  1189.          // all
  1190.          case TW_NO_INFO:   // no state information
  1191.            break;

  1192.          case TW_BUS_ERROR: // bus error, illegal stop/start
  1193.            twi_error = TW_BUS_ERROR;
  1194.            twi_stop();
  1195.            break;
  1196.        }

  1197.        if (fNextInterruptFunction) return fNextInterruptFunction();
  1198.    }

  1199.    TwoWire::TwoWire() { }
  1200.   
  1201.    void TwoWire::begin(void) {
  1202.        rxBufferIndex = 0;
  1203.        rxBufferLength = 0;
  1204.   
  1205.        txBufferIndex = 0;
  1206.        txBufferLength = 0;

  1207.        twi_init();
  1208.    }
  1209.   
  1210.    void TwoWire::beginTransmission(uint8_t address) {
  1211.        //beginTransmission((uint8_t)address);

  1212.        // indicate that we are transmitting
  1213.        twi_transmitting = 1;
  1214.       
  1215.        // set address of targeted slave
  1216.        txAddress = address;
  1217.       
  1218.        // reset tx buffer iterator vars
  1219.        txBufferIndex = 0;
  1220.        txBufferLength = 0;
  1221.    }

  1222.    uint8_t TwoWire::endTransmission(uint16_t timeout) {
  1223.        // transmit buffer (blocking)
  1224.        //int8_t ret =
  1225.        twi_cbendTransmissionDone = NULL;
  1226.        twi_writeTo(txAddress, txBuffer, txBufferLength, 1);
  1227.        int8_t ret = twii_WaitForDone(timeout);

  1228.        // reset tx buffer iterator vars
  1229.        txBufferIndex = 0;
  1230.        txBufferLength = 0;

  1231.        // indicate that we are done transmitting
  1232.        // twi_transmitting = 0;
  1233.        return ret;
  1234.    }

  1235.    void TwoWire::nbendTransmission(void (*function)(int)) {
  1236.        twi_cbendTransmissionDone = function;
  1237.        twi_writeTo(txAddress, txBuffer, txBufferLength, 1);
  1238.        return;
  1239.    }
  1240.   
  1241.    void TwoWire::send(uint8_t data) {
  1242.        if (twi_transmitting) {
  1243.          // in master transmitter mode
  1244.          // don't bother if buffer is full
  1245.          if (txBufferLength >= NBWIRE_BUFFER_LENGTH) {
  1246.            return;
  1247.          }

  1248.          // put byte in tx buffer
  1249.          txBuffer[txBufferIndex] = data;
  1250.          ++txBufferIndex;

  1251.          // update amount in buffer
  1252.          txBufferLength = txBufferIndex;
  1253.        } else {
  1254.          // in slave send mode
  1255.          // reply to master
  1256.          //twi_transmit(&data, 1);
  1257.        }
  1258.    }
  1259.   
  1260.    uint8_t TwoWire::receive(void) {
  1261.        // default to returning null char
  1262.        // for people using with char strings
  1263.        uint8_t value = 0;
  1264.     
  1265.        // get each successive byte on each call
  1266.        if (rxBufferIndex< rxBufferLength) {
  1267.          value = rxBuffer[rxBufferIndex];
  1268.          ++rxBufferIndex;
  1269.        }
  1270.   
  1271.        return value;
  1272.    }
  1273.   
  1274.    uint8_t TwoWire::requestFrom(uint8_t address, int quantity, uint16_t timeout) {
  1275.        // clamp to buffer length
  1276.        if (quantity > NBWIRE_BUFFER_LENGTH) {
  1277.          quantity = NBWIRE_BUFFER_LENGTH;
  1278.        }

  1279.        // perform blocking read into buffer
  1280.        twi_cbreadFromDone = NULL;
  1281.        twi_readFrom(address, rxBuffer, quantity);
  1282.        uint8_t read = twii_WaitForDone(timeout);

  1283.        // set rx buffer iterator vars
  1284.        rxBufferIndex = 0;
  1285.        rxBufferLength = read;
  1286.   
  1287.        return read;
  1288.    }
  1289.   
  1290.    void TwoWire::nbrequestFrom(uint8_t address, int quantity, void (*function)(int)) {
  1291.        // clamp to buffer length
  1292.        if (quantity > NBWIRE_BUFFER_LENGTH) {
  1293.          quantity = NBWIRE_BUFFER_LENGTH;
  1294.        }

  1295.        // perform blocking read into buffer
  1296.        twi_cbreadFromDone = function;
  1297.        twi_readFrom(address, rxBuffer, quantity);
  1298.        //uint8_t read = twii_WaitForDone();

  1299.        // set rx buffer iterator vars
  1300.        //rxBufferIndex = 0;
  1301.        //rxBufferLength = read;

  1302.        rxBufferIndex = 0;
  1303.        rxBufferLength = quantity; // this is a hack

  1304.        return; //read;
  1305.    }

  1306.    uint8_t TwoWire::available(void) {
  1307.        return rxBufferLength - rxBufferIndex;
  1308.    }

  1309. #endif
复制代码




评分

黑币 +50
收起理由
+ 50
共享资料的黑币奖励!

查看全部评分

沙发
ID:592703发表于 2019-9-9 17:56|只看该作者
谢谢!!!!
板凳
ID:263653发表于 2021-3-25 11:47|只看该作者
找了好久终于找到了谢谢
地板
ID:1129190发表于 2024-7-17 22:35|只看该作者
好吧,我现在只能学习学习,第一次搞一个328P的开发板,现在头都要大了,搞电子积木,快疯了
5#
ID:1130736发表于 2024-8-20 16:26|只看该作者
谢谢楼主了,找了好久

手机版|小黑屋|51黑电子论坛|51黑电子论坛6群QQ管理员QQ:125739409;技术交流QQ群281945664

Powered by 单片机教程网