OneWire.cpp 17 KB

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