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