DS18B20 — pymcu.drivers.ds18b20#

from pymcu.drivers.ds18b20 import DS18B20

1-Wire temperature sensor driver. Returns a 12-bit raw reading in 1/16 °C units.


class DS18B20#

DS18B20(pin: str)#

Binds the driver to a GPIO pin at compile time. The pin must be on PORTD (ATmega328P). No SRAM is allocated — the pin name is a compile-time constant.

Methods#

Method

Return type

Description

read() -> int16

int16

Full 1-Wire read; returns raw 12-bit value (1/16 °C) or -32768 on error

read_celsius_x16() -> int16

int16

Alias for read() — same result

Return value encoding#

Raw value

Meaning

>= 0

Temperature in 1/16 °C units

-32768

Sensor error (timeout, no device, CRC fail)

To convert to integer °C:

raw: int16 = sensor.read()
if raw != -32768:
    temp_c: int = raw >> 4          # integer part
    frac:   int = (raw & 0xF) * 625 # fractional part × 10000 µ°C

Examples#

Basic temperature read#

from pymcu.drivers.ds18b20 import DS18B20
from pymcu.hal.uart import UART
from pymcu.time import delay_ms
from pymcu.types import int16

def main():
    sensor = DS18B20("PD4")
    uart = UART(9600)
    uart.println("DS18B20 ready")

    while True:
        raw: int16 = sensor.read()
        if raw == -32768:
            uart.println("sensor error")
        else:
            temp_c: int = raw >> 4
            uart.write_str("temp=")
            uart.print_byte(temp_c)
        delay_ms(1000)

Wiring#

Arduino Uno          DS18B20
-----------          -------
PD4 (D4)    ←→      DATA
5V          ←→      VCC
GND         ←→      GND

Add a 4.7 kΩ pull-up resistor between DATA and VCC. The pull-up is required for the open-drain 1-Wire bus.


Notes#

  • Only one sensor per pin is supported (no multi-drop addressing in this driver).

  • Conversion time is 750 ms for 12-bit resolution — read() waits for the conversion to complete.

  • The driver uses delay_us() for precise 1-Wire timing; interrupts should be disabled during the read if timing-sensitive ISRs are active.

  • PORTD only (ATmega328P pin mapping constraint). Pins: "PD0""PD7" (D0–D7 on Arduino Uno).


See also#