I2Cdev.cpp 55 KB

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