Skip to content

File espos_onewire.h

File List > espos_sensors > include > espos_onewire.h

Go to the documentation of this file

/*
 * SPDX-FileCopyrightText: 2026 Dirk Wahrheit
 * SPDX-License-Identifier: Apache-2.0
 *
 * espos_onewire — a 1-Wire bus and the DS18B20s on it.
 *
 * The DS18B20 is the temperature sensor on boats: a few euro, waterproof
 * versions on a lead, and a dozen of them share three wires. Engine room,
 * fridge, freezer, cabin, water tank -- one bus.
 *
 * Wrapped over the registry components `espressif/ds18b20` and
 * `espressif/onewire_bus`, which IDF's own example uses. The wrapper exists
 * for two reasons that matter on a real boat:
 *
 *   * Enumeration by address, kept stable. Each sensor has a unique 64-bit
 *     ROM id, and that id -- not the order it answered in -- is what a
 *     Signal K path must key on. Sensors answer in address order, but a
 *     sensor that fails to answer one scan shifts every "index" after it,
 *     and the engine-room reading silently becomes the fridge.
 *   * A conversion that does not block the flow task for 750 ms. At 12-bit
 *     resolution the chip needs three quarters of a second to convert, and
 *     the honest way to use that in a graph is trigger-now / read-later.
 *
 * Needs an external 4.7 kOhm pull-up from the data line to 3V3. The internal
 * one cannot supply a DS18B20 and the bus reads as empty without it.
 */
#pragma once

#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include "esp_err.h"

#ifdef __cplusplus
extern "C" {
#endif

typedef struct espos_onewire_bus *espos_onewire_bus_handle_t;
typedef struct espos_ds18b20 *espos_ds18b20_handle_t;

esp_err_t espos_onewire_open(int gpio, espos_onewire_bus_handle_t *out);
void espos_onewire_close(espos_onewire_bus_handle_t bus);

esp_err_t espos_onewire_search(espos_onewire_bus_handle_t bus, uint64_t *addrs, size_t max, size_t *out_n);

esp_err_t espos_ds18b20_open(espos_onewire_bus_handle_t bus, uint64_t addr, espos_ds18b20_handle_t *out);
void espos_ds18b20_close(espos_ds18b20_handle_t dev);

esp_err_t espos_ds18b20_set_resolution(espos_ds18b20_handle_t dev, int bits);

esp_err_t espos_onewire_convert_all(espos_onewire_bus_handle_t bus);
uint32_t espos_ds18b20_convert_ms(int bits);

esp_err_t espos_ds18b20_read_kelvin(espos_ds18b20_handle_t dev, float *out_kelvin);

uint64_t espos_ds18b20_address(espos_ds18b20_handle_t dev);

#ifdef __cplusplus
}
#endif