選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

I2Cdev.cpp 55KB

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