onewire: Bit-banging 1-Wire driver
The Dallas 1-Wire bus needs one GPIO and one pull-up resistor, and no peripheral at all: every pulse on the line is produced by the CPU. This component is such a bit-banging master — it resets the bus, writes and reads bytes, selects devices by their ROM address, enumerates the bus and computes the CRCs the protocol uses. Devices such as the DS18B20 are driven on top of it (see ds18x20), and it runs on every ESP32 series chip and on the ESP8266.
Features
Reset and presence detection, byte and bit transfers, ROM select and skip ROM.
Bus enumeration with the standard search algorithm, with or without a family code filter, so a bus may hold devices of several kinds.
Strong pull-up for parasitically powered devices:
onewire_power()drives the line high with the pin itself,onewire_depower()gives it back to the pull-up resistor, and a reset does the same automatically.Dallas CRC8 for ROM codes and scratchpads, and CRC16 with the inverted form that devices send.
No hardware peripheral, no interrupt handlers, no task: everything runs in the caller’s context.
Wiring
Signal |
Connection |
|---|---|
DQ |
Any GPIO, one pin per bus |
VDD, GND |
Power and ground of the devices |
Pull-up |
4.7 kΩ from DQ to 3.3 V |
The driver configures the pin as an open-drain output with the internal pull-up enabled, so on a breadboard with a short bus nothing else is needed: the internal pull-up of an ESP32, roughly 45 kΩ, is enough for a couple of devices and a few centimetres of wire. That is not the 4.7 kΩ the datasheets ask for, though, and it becomes unreliable with longer wires, more devices or parasitic power. For anything beyond a quick test, add the external resistor.
A bus is not a tree: the pull-up sits at one end, the devices hang off the wire, and long stubs make the edges ring. A star with four sensors on one pin is how “random” CRC errors are usually made.
Timing
The protocol is timing-critical, and the timings are busy-waits: a bit takes about 70 µs, a byte about 560 µs, a reset cycle about 1 ms. Enumeration costs roughly 1 ms per device and ROM bit, so a bus with several sensors takes a few milliseconds to scan.
Each bit is transferred inside a critical section, so interrupts are disabled for up to about 80 µs, not for a whole byte: other drivers keep working, but their handlers should stay short. The functions must not be called from an interrupt handler themselves.
The component is not thread-safe. Call it from one task, or take your own mutex around every exchange with the bus: the library has no lock of its own, because a lock cannot protect the critical sections that the protocol needs.
ROM address
Every device has a 64-bit ROM code, which the driver keeps in a
onewire_addr_t. The least significant byte is the family code: 0x28 for
the DS18B20, 0x10 for the DS18S20, 0x3B for the MAX31850, and so on. Two
devices of the same kind can share a bus, so the ROM code, not the family,
identifies an address.
ONEWIRE_NONE is a value that cannot be a valid ROM code (its CRC does not
match) and is returned by onewire_search_next() when there is nothing more
to find.
CRC8 and espressif/onewire_bus
espressif/onewire_bus exports a function called onewire_crc8() as well,
with a different signature, so the two components cannot both link their symbol
into one binary. The implementation here is therefore exported as
onewire_crc8_dallas(), and onewire_crc8() is an inline wrapper that keeps
the old name working for existing code.
Code that calls the Espressif function on purpose has to include
onewire_crc.h and call onewire_crc8(0, data, len) with its three
arguments; the wrapper of this component takes two.
Configuration
Option |
Default |
Meaning |
|---|---|---|
|
|
Compute CRC8 from a table in flash instead of bit by bit |
Example
examples/default is a complete 1-Wire application: it reads a DS18B20 through
the ds18x20 driver, with the bus pin and the sensor address taken from
menuconfig. It doubles as a demonstration of how this component is used from
a device driver.
API reference
Defines
- ONEWIRE_NONE
ONEWIRE_NONE is an invalid ROM address that will never occur in a device (CRC mismatch), and so can be useful as an indicator for “no-such-device”, etc.
Typedefs
- typedef uint64_t onewire_addr_t
Type used to hold all 1-Wire device ROM addresses (64-bit)
Functions
- bool onewire_reset(gpio_num_t pin)
Perform a 1-Wire reset cycle.
The reset cycle also depowers the bus if onewire_power() was called before and leaves the pin in open-drain mode with the internal pull-up enabled.
- Parameters:
pin – The GPIO pin connected to the 1-Wire bus.
- Returns:
trueif at least one device responds with a presence pulse,falseif no devices were detected (or the bus is shorted, etc)
- bool onewire_select(gpio_num_t pin, const onewire_addr_t addr)
Issue a 1-Wire “ROM select” command to select a particular device.
It is necessary to call onewire_reset() before calling this function.
- Parameters:
pin – The GPIO pin connected to the 1-Wire bus.
addr – The ROM address of the device to select
- Returns:
trueif the “ROM select” command could be successfully issued,falseif there was an error.
- bool onewire_skip_rom(gpio_num_t pin)
Issue a 1-Wire “skip ROM” command to select all devices on the bus.
It is necessary to call onewire_reset() before calling this function.
- Parameters:
pin – The GPIO pin connected to the 1-Wire bus.
- Returns:
trueif the “skip ROM” command could be successfully issued,falseif there was an error.
- bool onewire_write(gpio_num_t pin, uint8_t v)
Write a byte on the onewire bus.
The writing code uses open-drain mode and expects the pullup resistor to pull the line high when not driven low. If you need strong power after the write (e.g. DS18B20 in parasite power mode) then call onewire_power() after this is complete to actively drive the line high.
- Parameters:
pin – The GPIO pin connected to the 1-Wire bus.
v – The byte value to write
- Returns:
trueif successful,falseon error.
- bool onewire_write_bytes(gpio_num_t pin, const uint8_t *buf, size_t count)
Write multiple bytes on the 1-Wire bus.
See onewire_write() for more info.
- Parameters:
pin – The GPIO pin connected to the 1-Wire bus.
buf – A pointer to the buffer of bytes to be written
count – Number of bytes to write
- Returns:
trueif all bytes written successfully,falseon error.
- int onewire_read(gpio_num_t pin)
Read a byte from a 1-Wire device.
- Parameters:
pin – The GPIO pin connected to the 1-Wire bus.
- Returns:
the byte read, 0..255, or -1 if the bus could not be released by the devices (a shorted or a stuck bus)
- bool onewire_read_bytes(gpio_num_t pin, uint8_t *buf, size_t count)
Read multiple bytes from a 1-Wire device.
- Parameters:
pin – The GPIO pin connected to the 1-Wire bus.
buf – [out] A pointer to the buffer to contain the read bytes
count – Number of bytes to read
- Returns:
trueon success,falseon error.
- bool onewire_power(gpio_num_t pin)
Actively drive the bus high to provide extra power for certain operations of parasitically-powered devices.
For parasitically-powered devices which need more power than can be provided via the normal pull-up resistor, it may be necessary for some operations to drive the bus actively high. This function can be used to perform that operation.
The bus can be depowered once it is no longer needed by calling onewire_depower(), or it will be depowered automatically the next time onewire_reset() is called to start another command.
While the bus is powered the pin is a push-pull output, not an open-drain one, so the line is held high by the GPIO itself. onewire_depower() and onewire_reset() return the pin to open-drain mode.
Note
Make sure the device(s) you are powering will not pull more current than the ESP32/ESP8266 is able to supply via its GPIO pins (this is especially important when multiple devices are on the same bus and they are all performing a power-intensive operation at the same time (i.e. multiple DS18B20 sensors, which have all been given a “convert T” operation by using onewire_skip_rom())).
Note
This routine will check to make sure that the bus is already high before driving it, to make sure it doesn’t attempt to drive it high while something else is pulling it low (which could cause a reset or damage the ESP32/ESP8266).
- Parameters:
pin – The GPIO pin connected to the 1-Wire bus.
- Returns:
trueon success,falseif the line stayed low, in which case nothing was driven
- void onewire_depower(gpio_num_t pin)
Stop forcing power onto the bus.
You only need to do this if you previously called onewire_power() to drive the bus high and now want to allow it to float instead. Note that onewire_reset() will also automatically depower the bus first, so you do not need to call this first if you just want to start a new operation.
- Parameters:
pin – The GPIO pin connected to the 1-Wire bus.
- void onewire_search_start(onewire_search_t *search)
Clear the search state so that it will start from the beginning on the next call to onewire_search_next().
- Parameters:
search – [out] The onewire_search_t structure to reset.
- void onewire_search_prefix(onewire_search_t *search, uint8_t family_code)
Setup the search to search for devices with the specified “family code”.
Call this instead of onewire_search_start() when only one kind of device is of interest: the enumeration then returns the members of that family and nothing else.
- Parameters:
search – [out] The onewire_search_t structure to update.
family_code – The “family code” to search for, the least significant byte of the ROM code (for example, 0x28 for a DS18B20).
- onewire_addr_t onewire_search_next(onewire_search_t *search, gpio_num_t pin)
Search for the next device on the bus.
The order of returned device addresses is deterministic. You will always get the same devices in the same order.
- Example
onewire_search_t search; onewire_addr_t addr; onewire_search_start(&search); while ((addr = onewire_search_next(&search, pin)) != ONEWIRE_NONE) { // use the device }Note
It might be a good idea to check the CRC to make sure you didn’t get garbage: on a noisy bus the search returns codes that no device has. onewire_crc8() over the eight bytes of the address answers that.
- Returns:
the address of the next device on the bus, or ONEWIRE_NONE if there is no next address. ONEWIRE_NONE might also mean that the bus is shorted, there are no devices, or you have already retrieved all of them.
- uint8_t onewire_crc8_dallas(const uint8_t *data, uint8_t len)
Compute a Dallas Semiconductor 8 bit CRC.
These are used in the ROM address and scratchpad registers to verify the transmitted data is correct.
Note
The implementation is exported under the name
onewire_crc8_dallas, because espressif/onewire_bus exportsonewire_crc8with a different signature and two symbols with the same name cannot coexist in one binary.
- Parameters:
data – Data to compute the CRC of
len – Number of bytes
- Returns:
The CRC
- static inline uint8_t onewire_crc8(const uint8_t *data, uint8_t len)
Compute a Dallas Semiconductor 8 bit CRC.
- Parameters:
data – Data to compute the CRC of
len – Number of bytes
- Returns:
The CRC
- bool onewire_check_crc16(const uint8_t *input, size_t len, const uint8_t *inverted_crc, uint16_t crc_iv)
Compute the 1-Wire CRC16 and compare it against the received CRC.
Example usage (reading a DS2408):
// Put everything in a buffer so we can compute the CRC easily. uint8_t buf[13]; buf[0] = 0xF0; // Read PIO Registers buf[1] = 0x88; // LSB address buf[2] = 0x00; // MSB address onewire_write_bytes(pin, buf, 3); // Write 3 cmd bytes onewire_read_bytes(pin, buf+3, 10); // Read 6 data bytes, 2 0xFF, 2 CRC16 if (!onewire_check_crc16(buf, 11, &buf[11])) { // TODO: Handle error. }
- Parameters:
input – Array of bytes to checksum.
len – Number of bytes in
inputinverted_crc – The two CRC16 bytes in the received data. This should just point into the received data, not at a 16-bit integer.
crc_iv – The crc starting value (optional)
- Returns:
trueif the CRC matches,falseotherwise.
- uint16_t onewire_crc16(const uint8_t *input, size_t len, uint16_t crc_iv)
Compute a Dallas Semiconductor 16 bit CRC.
This is required to check the integrity of data received from many 1-Wire devices. Note that the CRC computed here is not what you’ll get from the 1-Wire network, for two reasons:
The CRC is transmitted bitwise inverted.
Depending on the endian-ness of your processor, the binary representation of the two-byte return value may have a different byte order than the two bytes you get from 1-Wire.
- Parameters:
input – Array of bytes to checksum.
len – How many bytes are in
input.crc_iv – The crc starting value (optional)
- Returns:
the CRC16, as defined by Dallas Semiconductor.
- struct onewire_search_t
#include <onewire.h>Structure to contain the current state for onewire_search_next(), etc.