OneWire.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. /*
  2. Copyright (c) 2007, Jim Studt (original old version - many contributors since)
  3. The latest version of this library may be found at:
  4. http://www.pjrc.com/teensy/td_libs_OneWire.html
  5. OneWire has been maintained by Paul Stoffregen (paul@pjrc.com) since
  6. January 2010.
  7. DO NOT EMAIL for technical support, especially not for ESP chips!
  8. All project support questions must be posted on public forums
  9. relevant to the board or chips used. If using Arduino, post on
  10. Arduino's forum. If using ESP, post on the ESP community forums.
  11. There is ABSOLUTELY NO TECH SUPPORT BY PRIVATE EMAIL!
  12. Github's issue tracker for OneWire should be used only to report
  13. specific bugs. DO NOT request project support via Github. All
  14. project and tech support questions must be posted on forums, not
  15. github issues. If you experience a problem and you are not
  16. absolutely sure it's an issue with the library, ask on a forum
  17. first. Only use github to report issues after experts have
  18. confirmed the issue is with OneWire rather than your project.
  19. Back in 2010, OneWire was in need of many bug fixes, but had
  20. been abandoned the original author (Jim Studt). None of the known
  21. contributors were interested in maintaining OneWire. Paul typically
  22. works on OneWire every 6 to 12 months. Patches usually wait that
  23. long. If anyone is interested in more actively maintaining OneWire,
  24. please contact Paul (this is pretty much the only reason to use
  25. private email about OneWire).
  26. OneWire is now very mature code. No changes other than adding
  27. definitions for newer hardware support are anticipated.
  28. Version 2.3:
  29. Unknown chip fallback mode, Roger Clark
  30. Teensy-LC compatibility, Paul Stoffregen
  31. Search bug fix, Love Nystrom
  32. Version 2.2:
  33. Teensy 3.0 compatibility, Paul Stoffregen, paul@pjrc.com
  34. Arduino Due compatibility, http://arduino.cc/forum/index.php?topic=141030
  35. Fix DS18B20 example negative temperature
  36. Fix DS18B20 example's low res modes, Ken Butcher
  37. Improve reset timing, Mark Tillotson
  38. Add const qualifiers, Bertrik Sikken
  39. Add initial value input to crc16, Bertrik Sikken
  40. Add target_search() function, Scott Roberts
  41. Version 2.1:
  42. Arduino 1.0 compatibility, Paul Stoffregen
  43. Improve temperature example, Paul Stoffregen
  44. DS250x_PROM example, Guillermo Lovato
  45. PIC32 (chipKit) compatibility, Jason Dangel, dangel.jason AT gmail.com
  46. Improvements from Glenn Trewitt:
  47. - crc16() now works
  48. - check_crc16() does all of calculation/checking work.
  49. - Added read_bytes() and write_bytes(), to reduce tedious loops.
  50. - Added ds2408 example.
  51. Delete very old, out-of-date readme file (info is here)
  52. Version 2.0: Modifications by Paul Stoffregen, January 2010:
  53. http://www.pjrc.com/teensy/td_libs_OneWire.html
  54. Search fix from Robin James
  55. http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1238032295/27#27
  56. Use direct optimized I/O in all cases
  57. Disable interrupts during timing critical sections
  58. (this solves many random communication errors)
  59. Disable interrupts during read-modify-write I/O
  60. Reduce RAM consumption by eliminating unnecessary
  61. variables and trimming many to 8 bits
  62. Optimize both crc8 - table version moved to flash
  63. Modified to work with larger numbers of devices - avoids loop.
  64. Tested in Arduino 11 alpha with 12 sensors.
  65. 26 Sept 2008 -- Robin James
  66. http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1238032295/27#27
  67. Updated to work with arduino-0008 and to include skip() as of
  68. 2007/07/06. --RJL20
  69. Modified to calculate the 8-bit CRC directly, avoiding the need for
  70. the 256-byte lookup table to be loaded in RAM. Tested in arduino-0010
  71. -- Tom Pollard, Jan 23, 2008
  72. Jim Studt's original library was modified by Josh Larios.
  73. Tom Pollard, pollard@alum.mit.edu, contributed around May 20, 2008
  74. Permission is hereby granted, free of charge, to any person obtaining
  75. a copy of this software and associated documentation files (the
  76. "Software"), to deal in the Software without restriction, including
  77. without limitation the rights to use, copy, modify, merge, publish,
  78. distribute, sublicense, and/or sell copies of the Software, and to
  79. permit persons to whom the Software is furnished to do so, subject to
  80. the following conditions:
  81. The above copyright notice and this permission notice shall be
  82. included in all copies or substantial portions of the Software.
  83. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  84. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  85. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  86. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  87. LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  88. OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  89. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  90. Much of the code was inspired by Derek Yerger's code, though I don't
  91. think much of that remains. In any event that was..
  92. (copyleft) 2006 by Derek Yerger - Free to distribute freely.
  93. The CRC code was excerpted and inspired by the Dallas Semiconductor
  94. sample code bearing this copyright.
  95. //---------------------------------------------------------------------------
  96. // Copyright (C) 2000 Dallas Semiconductor Corporation, All Rights Reserved.
  97. //
  98. // Permission is hereby granted, free of charge, to any person obtaining a
  99. // copy of this software and associated documentation files (the "Software"),
  100. // to deal in the Software without restriction, including without limitation
  101. // the rights to use, copy, modify, merge, publish, distribute, sublicense,
  102. // and/or sell copies of the Software, and to permit persons to whom the
  103. // Software is furnished to do so, subject to the following conditions:
  104. //
  105. // The above copyright notice and this permission notice shall be included
  106. // in all copies or substantial portions of the Software.
  107. //
  108. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  109. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  110. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  111. // IN NO EVENT SHALL DALLAS SEMICONDUCTOR BE LIABLE FOR ANY CLAIM, DAMAGES
  112. // OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  113. // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  114. // OTHER DEALINGS IN THE SOFTWARE.
  115. //
  116. // Except as contained in this notice, the name of Dallas Semiconductor
  117. // shall not be used except as stated in the Dallas Semiconductor
  118. // Branding Policy.
  119. //--------------------------------------------------------------------------
  120. */
  121. #include <Arduino.h>
  122. #include "OneWire.h"
  123. #include "util/OneWire_direct_gpio.h"
  124. void OneWire::begin(uint8_t pin)
  125. {
  126. pinMode(pin, INPUT);
  127. bitmask = PIN_TO_BITMASK(pin);
  128. baseReg = PIN_TO_BASEREG(pin);
  129. #if ONEWIRE_SEARCH
  130. reset_search();
  131. #endif
  132. }
  133. // Perform the onewire reset function. We will wait up to 250uS for
  134. // the bus to come high, if it doesn't then it is broken or shorted
  135. // and we return a 0;
  136. //
  137. // Returns 1 if a device asserted a presence pulse, 0 otherwise.
  138. //
  139. uint8_t OneWire::reset(void)
  140. {
  141. IO_REG_TYPE mask IO_REG_MASK_ATTR = bitmask;
  142. volatile IO_REG_TYPE *reg IO_REG_BASE_ATTR = baseReg;
  143. uint8_t r;
  144. uint8_t retries = 125;
  145. noInterrupts();
  146. DIRECT_MODE_INPUT(reg, mask);
  147. interrupts();
  148. // wait until the wire is high... just in case
  149. do {
  150. if (--retries == 0) return 0;
  151. delayMicroseconds(2);
  152. } while ( !DIRECT_READ(reg, mask));
  153. noInterrupts();
  154. DIRECT_WRITE_LOW(reg, mask);
  155. DIRECT_MODE_OUTPUT(reg, mask); // drive output low
  156. interrupts();
  157. delayMicroseconds(480);
  158. noInterrupts();
  159. DIRECT_MODE_INPUT(reg, mask); // allow it to float
  160. delayMicroseconds(70);
  161. r = !DIRECT_READ(reg, mask);
  162. interrupts();
  163. delayMicroseconds(410);
  164. return r;
  165. }
  166. //
  167. // Write a bit. Port and bit is used to cut lookup time and provide
  168. // more certain timing.
  169. //
  170. void OneWire::write_bit(uint8_t v)
  171. {
  172. IO_REG_TYPE mask IO_REG_MASK_ATTR = bitmask;
  173. volatile IO_REG_TYPE *reg IO_REG_BASE_ATTR = baseReg;
  174. if (v & 1) {
  175. noInterrupts();
  176. DIRECT_WRITE_LOW(reg, mask);
  177. DIRECT_MODE_OUTPUT(reg, mask); // drive output low
  178. delayMicroseconds(10);
  179. DIRECT_WRITE_HIGH(reg, mask); // drive output high
  180. interrupts();
  181. delayMicroseconds(55);
  182. } else {
  183. noInterrupts();
  184. DIRECT_WRITE_LOW(reg, mask);
  185. DIRECT_MODE_OUTPUT(reg, mask); // drive output low
  186. delayMicroseconds(65);
  187. DIRECT_WRITE_HIGH(reg, mask); // drive output high
  188. interrupts();
  189. delayMicroseconds(5);
  190. }
  191. }
  192. //
  193. // Read a bit. Port and bit is used to cut lookup time and provide
  194. // more certain timing.
  195. //
  196. uint8_t OneWire::read_bit(void)
  197. {
  198. IO_REG_TYPE mask IO_REG_MASK_ATTR = bitmask;
  199. volatile IO_REG_TYPE *reg IO_REG_BASE_ATTR = baseReg;
  200. uint8_t r;
  201. noInterrupts();
  202. DIRECT_MODE_OUTPUT(reg, mask);
  203. DIRECT_WRITE_LOW(reg, mask);
  204. delayMicroseconds(3);
  205. DIRECT_MODE_INPUT(reg, mask); // let pin float, pull up will raise
  206. delayMicroseconds(10);
  207. r = DIRECT_READ(reg, mask);
  208. interrupts();
  209. delayMicroseconds(53);
  210. return r;
  211. }
  212. //
  213. // Write a byte. The writing code uses the active drivers to raise the
  214. // pin high, if you need power after the write (e.g. DS18S20 in
  215. // parasite power mode) then set 'power' to 1, otherwise the pin will
  216. // go tri-state at the end of the write to avoid heating in a short or
  217. // other mishap.
  218. //
  219. void OneWire::write(uint8_t v, uint8_t power /* = 0 */) {
  220. uint8_t bitMask;
  221. for (bitMask = 0x01; bitMask; bitMask <<= 1) {
  222. OneWire::write_bit( (bitMask & v)?1:0);
  223. }
  224. if ( !power) {
  225. noInterrupts();
  226. DIRECT_MODE_INPUT(baseReg, bitmask);
  227. DIRECT_WRITE_LOW(baseReg, bitmask);
  228. interrupts();
  229. }
  230. }
  231. void OneWire::write_bytes(const uint8_t *buf, uint16_t count, bool power /* = 0 */) {
  232. for (uint16_t i = 0 ; i < count ; i++)
  233. write(buf[i]);
  234. if (!power) {
  235. noInterrupts();
  236. DIRECT_MODE_INPUT(baseReg, bitmask);
  237. DIRECT_WRITE_LOW(baseReg, bitmask);
  238. interrupts();
  239. }
  240. }
  241. //
  242. // Read a byte
  243. //
  244. uint8_t OneWire::read() {
  245. uint8_t bitMask;
  246. uint8_t r = 0;
  247. for (bitMask = 0x01; bitMask; bitMask <<= 1) {
  248. if ( OneWire::read_bit()) r |= bitMask;
  249. }
  250. return r;
  251. }
  252. void OneWire::read_bytes(uint8_t *buf, uint16_t count) {
  253. for (uint16_t i = 0 ; i < count ; i++)
  254. buf[i] = read();
  255. }
  256. //
  257. // Do a ROM select
  258. //
  259. void OneWire::select(const uint8_t rom[8])
  260. {
  261. uint8_t i;
  262. write(0x55); // Choose ROM
  263. for (i = 0; i < 8; i++) write(rom[i]);
  264. }
  265. //
  266. // Do a ROM skip
  267. //
  268. void OneWire::skip()
  269. {
  270. write(0xCC); // Skip ROM
  271. }
  272. void OneWire::depower()
  273. {
  274. noInterrupts();
  275. DIRECT_MODE_INPUT(baseReg, bitmask);
  276. interrupts();
  277. }
  278. #if ONEWIRE_SEARCH
  279. //
  280. // You need to use this function to start a search again from the beginning.
  281. // You do not need to do it for the first search, though you could.
  282. //
  283. void OneWire::reset_search()
  284. {
  285. // reset the search state
  286. LastDiscrepancy = 0;
  287. LastDeviceFlag = false;
  288. LastFamilyDiscrepancy = 0;
  289. for(int i = 7; ; i--) {
  290. ROM_NO[i] = 0;
  291. if ( i == 0) break;
  292. }
  293. }
  294. // Setup the search to find the device type 'family_code' on the next call
  295. // to search(*newAddr) if it is present.
  296. //
  297. void OneWire::target_search(uint8_t family_code)
  298. {
  299. // set the search state to find SearchFamily type devices
  300. ROM_NO[0] = family_code;
  301. for (uint8_t i = 1; i < 8; i++)
  302. ROM_NO[i] = 0;
  303. LastDiscrepancy = 64;
  304. LastFamilyDiscrepancy = 0;
  305. LastDeviceFlag = false;
  306. }
  307. //
  308. // Perform a search. If this function returns a '1' then it has
  309. // enumerated the next device and you may retrieve the ROM from the
  310. // OneWire::address variable. If there are no devices, no further
  311. // devices, or something horrible happens in the middle of the
  312. // enumeration then a 0 is returned. If a new device is found then
  313. // its address is copied to newAddr. Use OneWire::reset_search() to
  314. // start over.
  315. //
  316. // --- Replaced by the one from the Dallas Semiconductor web site ---
  317. //--------------------------------------------------------------------------
  318. // Perform the 1-Wire Search Algorithm on the 1-Wire bus using the existing
  319. // search state.
  320. // Return TRUE : device found, ROM number in ROM_NO buffer
  321. // FALSE : device not found, end of search
  322. //
  323. bool OneWire::search(uint8_t *newAddr, bool search_mode /* = true */)
  324. {
  325. uint8_t id_bit_number;
  326. uint8_t last_zero, rom_byte_number;
  327. bool search_result;
  328. uint8_t id_bit, cmp_id_bit;
  329. unsigned char rom_byte_mask, search_direction;
  330. // initialize for search
  331. id_bit_number = 1;
  332. last_zero = 0;
  333. rom_byte_number = 0;
  334. rom_byte_mask = 1;
  335. search_result = false;
  336. // if the last call was not the last one
  337. if (!LastDeviceFlag) {
  338. // 1-Wire reset
  339. if (!reset()) {
  340. // reset the search
  341. LastDiscrepancy = 0;
  342. LastDeviceFlag = false;
  343. LastFamilyDiscrepancy = 0;
  344. return false;
  345. }
  346. // issue the search command
  347. if (search_mode == true) {
  348. write(0xF0); // NORMAL SEARCH
  349. } else {
  350. write(0xEC); // CONDITIONAL SEARCH
  351. }
  352. // loop to do the search
  353. do
  354. {
  355. // read a bit and its complement
  356. id_bit = read_bit();
  357. cmp_id_bit = read_bit();
  358. // check for no devices on 1-wire
  359. if ((id_bit == 1) && (cmp_id_bit == 1)) {
  360. break;
  361. } else {
  362. // all devices coupled have 0 or 1
  363. if (id_bit != cmp_id_bit) {
  364. search_direction = id_bit; // bit write value for search
  365. } else {
  366. // if this discrepancy if before the Last Discrepancy
  367. // on a previous next then pick the same as last time
  368. if (id_bit_number < LastDiscrepancy) {
  369. search_direction = ((ROM_NO[rom_byte_number] & rom_byte_mask) > 0);
  370. } else {
  371. // if equal to last pick 1, if not then pick 0
  372. search_direction = (id_bit_number == LastDiscrepancy);
  373. }
  374. // if 0 was picked then record its position in LastZero
  375. if (search_direction == 0) {
  376. last_zero = id_bit_number;
  377. // check for Last discrepancy in family
  378. if (last_zero < 9)
  379. LastFamilyDiscrepancy = last_zero;
  380. }
  381. }
  382. // set or clear the bit in the ROM byte rom_byte_number
  383. // with mask rom_byte_mask
  384. if (search_direction == 1)
  385. ROM_NO[rom_byte_number] |= rom_byte_mask;
  386. else
  387. ROM_NO[rom_byte_number] &= ~rom_byte_mask;
  388. // serial number search direction write bit
  389. write_bit(search_direction);
  390. // increment the byte counter id_bit_number
  391. // and shift the mask rom_byte_mask
  392. id_bit_number++;
  393. rom_byte_mask <<= 1;
  394. // if the mask is 0 then go to new SerialNum byte rom_byte_number and reset mask
  395. if (rom_byte_mask == 0) {
  396. rom_byte_number++;
  397. rom_byte_mask = 1;
  398. }
  399. }
  400. }
  401. while(rom_byte_number < 8); // loop until through all ROM bytes 0-7
  402. // if the search was successful then
  403. if (!(id_bit_number < 65)) {
  404. // search successful so set LastDiscrepancy,LastDeviceFlag,search_result
  405. LastDiscrepancy = last_zero;
  406. // check for last device
  407. if (LastDiscrepancy == 0) {
  408. LastDeviceFlag = true;
  409. }
  410. search_result = true;
  411. }
  412. }
  413. // if no device found then reset counters so next 'search' will be like a first
  414. if (!search_result || !ROM_NO[0]) {
  415. LastDiscrepancy = 0;
  416. LastDeviceFlag = false;
  417. LastFamilyDiscrepancy = 0;
  418. search_result = false;
  419. } else {
  420. for (int i = 0; i < 8; i++) newAddr[i] = ROM_NO[i];
  421. }
  422. return search_result;
  423. }
  424. #endif
  425. #if ONEWIRE_CRC
  426. // The 1-Wire CRC scheme is described in Maxim Application Note 27:
  427. // "Understanding and Using Cyclic Redundancy Checks with Maxim iButton Products"
  428. //
  429. #if ONEWIRE_CRC8_TABLE
  430. // Dow-CRC using polynomial X^8 + X^5 + X^4 + X^0
  431. // Tiny 2x16 entry CRC table created by Arjen Lentz
  432. // See http://lentz.com.au/blog/calculating-crc-with-a-tiny-32-entry-lookup-table
  433. static const uint8_t PROGMEM dscrc2x16_table[] = {
  434. 0x00, 0x5E, 0xBC, 0xE2, 0x61, 0x3F, 0xDD, 0x83,
  435. 0xC2, 0x9C, 0x7E, 0x20, 0xA3, 0xFD, 0x1F, 0x41,
  436. 0x00, 0x9D, 0x23, 0xBE, 0x46, 0xDB, 0x65, 0xF8,
  437. 0x8C, 0x11, 0xAF, 0x32, 0xCA, 0x57, 0xE9, 0x74
  438. };
  439. // Compute a Dallas Semiconductor 8 bit CRC. These show up in the ROM
  440. // and the registers. (Use tiny 2x16 entry CRC table)
  441. uint8_t OneWire::crc8(const uint8_t *addr, uint8_t len)
  442. {
  443. uint8_t crc = 0;
  444. while (len--) {
  445. crc = *addr++ ^ crc; // just re-using crc as intermediate
  446. crc = pgm_read_byte(dscrc2x16_table + (crc & 0x0f)) ^
  447. pgm_read_byte(dscrc2x16_table + 16 + ((crc >> 4) & 0x0f));
  448. }
  449. return crc;
  450. }
  451. #else
  452. //
  453. // Compute a Dallas Semiconductor 8 bit CRC directly.
  454. // this is much slower, but a little smaller, than the lookup table.
  455. //
  456. uint8_t OneWire::crc8(const uint8_t *addr, uint8_t len)
  457. {
  458. uint8_t crc = 0;
  459. while (len--) {
  460. #if defined(__AVR__)
  461. crc = _crc_ibutton_update(crc, *addr++);
  462. #else
  463. uint8_t inbyte = *addr++;
  464. for (uint8_t i = 8; i; i--) {
  465. uint8_t mix = (crc ^ inbyte) & 0x01;
  466. crc >>= 1;
  467. if (mix) crc ^= 0x8C;
  468. inbyte >>= 1;
  469. }
  470. #endif
  471. }
  472. return crc;
  473. }
  474. #endif
  475. #if ONEWIRE_CRC16
  476. bool OneWire::check_crc16(const uint8_t* input, uint16_t len, const uint8_t* inverted_crc, uint16_t crc)
  477. {
  478. crc = ~crc16(input, len, crc);
  479. return (crc & 0xFF) == inverted_crc[0] && (crc >> 8) == inverted_crc[1];
  480. }
  481. uint16_t OneWire::crc16(const uint8_t* input, uint16_t len, uint16_t crc)
  482. {
  483. #if defined(__AVR__)
  484. for (uint16_t i = 0 ; i < len ; i++) {
  485. crc = _crc16_update(crc, input[i]);
  486. }
  487. #else
  488. static const uint8_t oddparity[16] =
  489. { 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0 };
  490. for (uint16_t i = 0 ; i < len ; i++) {
  491. // Even though we're just copying a byte from the input,
  492. // we'll be doing 16-bit computation with it.
  493. uint16_t cdata = input[i];
  494. cdata = (cdata ^ crc) & 0xff;
  495. crc >>= 8;
  496. if (oddparity[cdata & 0x0F] ^ oddparity[cdata >> 4])
  497. crc ^= 0xC001;
  498. cdata <<= 6;
  499. crc ^= cdata;
  500. cdata <<= 1;
  501. crc ^= cdata;
  502. }
  503. #endif
  504. return crc;
  505. }
  506. #endif
  507. #endif