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 |
|---|---|---|
|
|
Full 1-Wire read; returns raw 12-bit value (1/16 °C) or |
|
|
Alias for |
Return value encoding#
Raw value |
Meaning |
|---|---|
|
Temperature in 1/16 °C units |
|
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#
DHT11 — combined temperature and humidity sensor
ADC — pymcu.hal.adc — internal temperature sensor (rough, uncalibrated)