I2Cdev.cpp 55 KB

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