Branch data Line data Source code
1 : : /**
2 : : * @file onewire.h
3 : : * @brief Universal non-blocking 1-Wire bus layer for STM32
4 : : * @details The driver (ds18b20.c) and any other 1-Wire slave driver (DS2413,
5 : : * DS2431, ...) are built on top of this layer. Every operation is
6 : : * scheduled on TIM1/DMA and completes asynchronously: callers poll
7 : : * onewire_bus_done() / onewire_search_poll() to advance, never wait.
8 : : * The layer owns TIM1, its DMA feed/capture pair and the bus GPIO pin
9 : : * from onewire_init() until reset (see there); access the bus only
10 : : * through this API.
11 : : */
12 : :
13 : : #ifndef ONEWIRE_H
14 : : #define ONEWIRE_H
15 : :
16 : : #include "ow_config.h"
17 : : #include "ow_version.h"
18 : : #include <stdint.h>
19 : :
20 : : #ifdef __cplusplus
21 : : extern "C" {
22 : : #endif
23 : :
24 : : /**
25 : : * @defgroup ONEWIRE_Protocol 1-Wire Protocol Constants
26 : : * @{
27 : : */
28 : :
29 : : /** @brief Bytes in a device ROM address */
30 : : #define ONEWIRE_ROM_BYTES 8
31 : : /** @brief Bits in a device ROM address */
32 : : #define ONEWIRE_ROM_BITS (ONEWIRE_ROM_BYTES * 8)
33 : : /** @brief Bits per byte */
34 : : #define ONEWIRE_BITS_PER_BYTE 8
35 : : /** @brief Maximum bit slots per hardware operation (TIM1 RCR is 8-bit: RCR = slots - 1) */
36 : : #define ONEWIRE_MAX_SLOTS 256u
37 : : /** @brief Maximum bytes per onewire_read_data() pass (256 slots / 8 bits) */
38 : : #define ONEWIRE_MAX_READ_BYTES (ONEWIRE_MAX_SLOTS / ONEWIRE_BITS_PER_BYTE)
39 : : /** @brief Value that releases the bus (idle HIGH) at the end of a multi-slot
40 : : * write or merged write+read operation.
41 : : * @note Pulse buffers for multi-slot writes must hold `slots + 1` entries:
42 : : * entries [0 .. slots-1] encode the transmitted slots and the entry at
43 : : * index `slots` must equal this value. The CCR3-feed DMA loads it during
44 : : * the final slot, so the one-pulse timer stops with the line already
45 : : * released to idle HIGH (hardware bus release — no software CCR3 write
46 : : * afterwards). It is not an additional 1-Wire slot. For a single-slot
47 : : * write (slots == 1) the backend uses a separate path without DMA and
48 : : * does not read entry `slots`. */
49 : : #define ONEWIRE_RELEASE_PULSE 0u
50 : : /** @brief 1-Wire ROM command: Search ROM (all devices respond with their ROM) */
51 : : #define ONEWIRE_SEARCH_ROM 0xF0
52 : : /** @brief 1-Wire ROM command: Alarm Search (only alarming devices respond) */
53 : : #define ONEWIRE_ALARM_SEARCH 0xEC
54 : : /** @brief 1-Wire ROM command: Match ROM (address one device by its 8-byte ROM) */
55 : : #define ONEWIRE_MATCH_ROM 0x55
56 : : /** @brief 1-Wire ROM command: Skip ROM (broadcast to every device on the bus) */
57 : : #define ONEWIRE_SKIP_ROM 0xCC
58 : : /** @brief Board facts: the family selection token and ow_pulse_t.
59 : : *
60 : : * The token resolves from the CMSIS device macro of the target (e.g.
61 : : * -DSTM32F030x6) or, for host-test mocks, PlatformIO and STM32CubeMX
62 : : * projects, from a family macro (STM32F0, STM32F1, STM32F3, STM32F4,
63 : : * STM32G0, STM32G4, STM32L4, STM32C5, STM32H5, STM32U5, STM32H7).
64 : : * Concrete device spellings are accepted for the parts this project supports
65 : : * (STM32F030x6 for F0; STM32F103xB for F1; STM32F303xC for F3;
66 : : * STM32F407xx / STM32F401xC / STM32F446xx for F4;
67 : : * STM32G031xx for G0; STM32G474xx for G4; STM32L476xx for L4;
68 : : * STM32C552xx for C5; STM32H503xx for H5; STM32U585xx for U5;
69 : : * STM32H743xx for H7).
70 : : * The token is the single point of family selection: app.c takes the device
71 : : * header and clock configuration from it, and the per-family facts
72 : : * ow_pulse_t and the OW_HSE_MHZ / OW_*_MAX_SYSCLK_MHZ defaults live in
73 : : * inc/ow_board.h beside it. The TIM1+DMA engine and the register-level
74 : : * per-family facts are library-internal and are not needed to use this
75 : : * API. To add a family, extend the dispatch in
76 : : * inc/ow_board.h (plus the \#error spelling list), the app.c clock/UART
77 : : * config, a chips/<part>.mk part file, the Makefile (OW_KNOWN_TARGETS, the
78 : : * OW_TARGET family block, the OW_MCU mapping entries, TEST_CLOCK_FLAG) and
79 : : * CMakeLists.txt (the OW_MCU mapping, the OW_TARGET branch, the default
80 : : * chip) wiring, the tests/mock device header, and a case in
81 : : * tests/test/test_sysclk_fallback.c. */
82 : : #include "ow_board.h"
83 : :
84 : : /** @} */
85 : :
86 : : /**
87 : : * @defgroup ONEWIRE_Init Init
88 : : * @{
89 : : */
90 : :
91 : : /**
92 : : * @brief Initialize the shared 1-Wire timer/DMA/GPIO resources
93 : : * @pre Call after MCU reset, before any 1-Wire bus operation or slave-driver
94 : : * activity. Initialize the system clock first when its final frequency is
95 : : * not the backend default.
96 : : * @note Enables the timer/DMA/GPIO clocks, sets the timer prescaler for 1µs
97 : : * resolution, configures the bus pin as alternate-function open-drain
98 : : * and marks the search engine idle. The timer is left stopped: the first
99 : : * operation only starts when the application requests it.
100 : : * @warning This is a bootstrap operation, not a reinitialization hook. A second
101 : : * call does not stop or reset an active TIM1/DMA operation, clear stale
102 : : * timer/DMA/low-power state, or fully reset slave-driver state. Calling
103 : : * it twice before any bus operation is harmless (it re-applies the same
104 : : * idle configuration, which is how all three slave drivers are brought
105 : : * up in one image); starting a new driver lifecycle requires an MCU
106 : : * reset.
107 : : * @warning After initialization the 1-Wire layer exclusively owns TIM1, the
108 : : * DMA feed/capture pair of the active backend (DMA1 channels 3 and 4
109 : : * on F0/F1/G0, DMA2 streams 2 and 4 on F4), and the bus GPIO pin
110 : : * including its alternate-function/remap configuration. Application
111 : : * code, ISRs and other drivers must not configure or use these
112 : : * resources while the layer is in use. The library has no deinit or
113 : : * release API: the ownership lasts until reset.
114 : : */
115 : : void onewire_init(void);
116 : :
117 : : /**
118 : : * @brief Configuration token the library was compiled with
119 : : * @return OW_CONFIG_TOKEN as seen by the library translation units
120 : : * @note Compare with the application-side OW_CONFIG_TOKEN at startup:
121 : : * a mismatch means the archive and the application were built with
122 : : * different OW flags, clock frequencies, or DS18B20_MAX_DEVICES. Fail
123 : : * loudly there instead of running with a silently different bus timing
124 : : * or table size.
125 : : */
126 : : uint32_t onewire_config_token(void);
127 : :
128 : : /**
129 : : * @brief Whether the runtime core clock agrees with the build
130 : : * @param[in] sysclk_mhz Core clock in whole MHz as the firmware actually
131 : : * runs, e.g. (SystemCoreClock / 1000000u)
132 : : * @return 1 when the core-clock reading matches OW_SYSCLK_MHZ
133 : : * @note Call once at startup before any bus operation and refuse to run on 0:
134 : : * with -DOW_SYSCLK_MHZ this validates the core clock; the timer
135 : : * prescaler is compiled from OW_TIM1_MHZ (defaults to OW_SYSCLK_MHZ).
136 : : * A split-clock target must configure TIM1 to that timer frequency.
137 : : * Without -DOW_SYSCLK_MHZ (SystemCoreClock auto-path) the port derives
138 : : * its timer prescaler from SystemCoreClock itself, so this only rejects
139 : : * a zero/uninitialized reading - staleness after a clock-tree change is
140 : : * undetectable here, call SystemCoreClockUpdate().
141 : : */
142 : : uint8_t onewire_clock_ok(uint32_t sysclk_mhz);
143 : :
144 : : /** @} */
145 : :
146 : : /**
147 : : * @defgroup ONEWIRE_Bus Non-Blocking 1-Wire Bus Primitives
148 : : * @brief Each primitive schedules exactly one hardware-timed operation on
149 : : * TIM1/DMA and returns immediately. Poll onewire_bus_done() to learn
150 : : * when the operation finished, then decode the result.
151 : : * @{
152 : : */
153 : :
154 : : /**
155 : : * @brief Non-blocking completion check for the scheduled bus operation
156 : : * @return 1 if finished (update flag cleared), 0 while still running
157 : : */
158 : : uint8_t onewire_bus_done(void);
159 : :
160 : : /**
161 : : * @brief Schedule a 1-Wire bus reset (presence pulse captured via DMA)
162 : : * @param[out] reset_pulses Buffer for the captured reset + presence pulse
163 : : * durations (2 x 16-bit; entry 1 is only valid when
164 : : * onewire_reset_captured() returns 2)
165 : : * @note On completion, call onewire_reset_captured() and pass its count,
166 : : * together with this buffer, to onewire_present().
167 : : */
168 : : void onewire_reset(volatile uint16_t* reset_pulses);
169 : :
170 : : /**
171 : : * @brief Edges captured by the last capture operation armed
172 : : * @return 0..2; after a reset, 2 means the presence edge arrived, 1 means
173 : : * only the master-release edge was captured, 0 means neither
174 : : * @note Read from the capture DMA's remaining-transfer count, so the value
175 : : * describes whatever capture was armed last - a reset, a read pair, a
176 : : * merged write+read or a data read - not the reset specifically. Every
177 : : * completed capture drains that counter, so after any of them this call
178 : : * returns 2 again; before the first reset it also returns 2, because the
179 : : * register is still at its reset value. Treat 2 as evidence only for a
180 : : * reset that onewire_reset() actually armed: read the count after that
181 : : * reset's onewire_bus_done() and before any other capture is armed, and
182 : : * pass it to onewire_present() with the buffer of the same reset.
183 : : */
184 : : uint8_t onewire_reset_captured(void);
185 : :
186 : : /**
187 : : * @brief Decode the presence pulse captured by onewire_reset()
188 : : * @param[in] pulses Reset + presence pulse durations captured by onewire_reset()
189 : : * @param[in] captured Edges captured by that reset; pass
190 : : * onewire_reset_captured()
191 : : * @return 1 if at least one device answered, 0 otherwise
192 : : * @note A reset that captured only the master-release edge has no presence
193 : : * entry; `captured` is what distinguishes it from a stale pulse[1],
194 : : * whose value may otherwise fall inside the presence window.
195 : : * `captured` must describe the same reset as `pulses`: the two are one
196 : : * hardware fact read from two places. Both go stale the moment another
197 : : * capture is armed - a later completed capture makes
198 : : * onewire_reset_captured() return 2 again, which would otherwise bless
199 : : * a stale pulses[1].
200 : : */
201 : : uint8_t onewire_present(const volatile uint16_t* pulses, uint8_t captured);
202 : :
203 : : /**
204 : : * @brief Schedule a write of `slots` bit slots
205 : : * @param[in] pulses Pulse buffer: one entry per slot, plus one trailing entry
206 : : * at index `slots` that must equal ONEWIRE_RELEASE_PULSE
207 : : * (hardware bus release) when `slots > 1`; in that case the
208 : : * buffer therefore holds `slots + 1` entries. A single-slot
209 : : * write (slots == 1) uses the DMA-free path and only reads
210 : : * entry 0.
211 : : * @param[in] slots Number of bit slots to transmit, 1..ONEWIRE_MAX_SLOTS (256).
212 : : * Out-of-range values (0 or > 256) are rejected: TIM1 RCR is
213 : : * 8-bit (RCR = slots - 1), so larger counts would truncate and
214 : : * desync the timer from the DMA (CNDTR).
215 : : * @return 1 if the write was scheduled, 0 if `slots` is out of range (the
216 : : * call is rejected and no operation is scheduled). In firmware the
217 : : * reject path returns 0; an assert is compiled in only under
218 : : * DS18B20_TEST_HARNESS or OW_TEST_PARAM_GUARD (and is disabled by
219 : : * NDEBUG).
220 : : * @note Non-blocking: the DMA feeds CCR3 from the buffer asynchronously, so
221 : : * the buffer must stay valid until onewire_bus_done() reports completion.
222 : : */
223 : : uint8_t onewire_write_slots(const ow_pulse_t* pulses, uint16_t slots);
224 : :
225 : : /**
226 : : * @brief Schedule a single-slot write of one raw bit
227 : : * @param[in] bit Bit value to write (0 or 1)
228 : : * @return 1 (the only valid range always schedules)
229 : : */
230 : : uint8_t onewire_write_bit(uint8_t bit);
231 : :
232 : : /**
233 : : * @brief Schedule a two-slot read of a Search ROM id/cmp bit pair
234 : : * @param[out] pair_pulses Buffer for the captured pulse durations (2 × 16-bit)
235 : : * @note On completion, decode the pair with onewire_pair_bits().
236 : : */
237 : : void onewire_read_pair(volatile uint16_t* pair_pulses);
238 : :
239 : : /**
240 : : * @brief Decode the id/cmp bits of a two-slot read pair
241 : : * @param[in] pair_pulses Pulses captured by onewire_read_pair()
242 : : * @param[out] id_bit Id bit (0 or 1)
243 : : * @param[out] cmp_bit Complement bit (0 or 1)
244 : : */
245 : : void onewire_pair_bits(const volatile uint16_t* pair_pulses, uint8_t* id_bit, uint8_t* cmp_bit);
246 : :
247 : : /**
248 : : * @brief Schedule a merged single-slot write followed by a two-slot read pair
249 : : * @param[in] bit Direction bit to write in slot 1 (0 or 1)
250 : : * @note One timer pass runs three slots: a write of `bit`, then a read of the
251 : : * next id/cmp pair. Halves the timer passes per search bit compared to a
252 : : * plain write plus a separate read pair. On completion, the internal
253 : : * merged buffer holds [write-slot capture, id pulse, cmp pulse]: decode the
254 : : * pair from entries 1 and 2 with onewire_bit_from_pulse(). Do not pass
255 : : * this buffer to onewire_pair_bits(), which instead decodes entries 0 and
256 : : * 1 as produced by onewire_read_pair().
257 : : */
258 : : void onewire_write_then_read(uint8_t bit);
259 : :
260 : : /**
261 : : * @brief Schedule a read of `bytes` bytes from the bus
262 : : * @param[out] dst Buffer for the captured pulse durations (bytes × 8 × 8-bit)
263 : : * @param[in] bytes Number of bytes to read, 1..ONEWIRE_MAX_READ_BYTES (32).
264 : : * Out-of-range values (0 or > 32) are rejected: one pass is
265 : : * limited to ONEWIRE_MAX_SLOTS (256) slots by the 8-bit TIM1
266 : : * RCR (RCR = bytes*8 - 1); larger reads must be split.
267 : : * @return 1 if the read was scheduled, 0 if `bytes` is out of range (the call
268 : : * is rejected and no operation is scheduled). In firmware the reject
269 : : * path returns 0; an assert is compiled in only under
270 : : * DS18B20_TEST_HARNESS or OW_TEST_PARAM_GUARD (and is disabled by
271 : : * NDEBUG).
272 : : * @note On completion, the caller decodes the 8-bit pulse durations (pulse
273 : : * `<= ONEWIRE_SHORT_PULSE_MAX` reads as bit 1) into data bytes.
274 : : */
275 : : uint8_t onewire_read_data(volatile uint8_t* dst, uint8_t bytes);
276 : :
277 : : /**
278 : : * @brief Decode a single captured pulse duration into a 1-Wire bit
279 : : * @param[in] dur Pulse duration in microseconds
280 : : * @return 1 if the pulse is short (bit value '1'), 0 if long (bit value '0')
281 : : * @note A pulse duration `<= ONEWIRE_SHORT_PULSE_MAX` is the short ('1') slot.
282 : : */
283 : 1504650 : static inline uint8_t onewire_bit_from_pulse(uint16_t dur) {
284 [ + + ]: 1504650 : return (dur <= ONEWIRE_SHORT_PULSE_MAX) ? 1u : 0u;
285 : : }
286 : :
287 : : /**
288 : : * @brief Decode captured pulse durations into data bytes (LSB-first bits)
289 : : * @param[out] dst Decoded bytes
290 : : * @param[in] pulse Captured per-bit pulse durations (one entry per bit)
291 : : * @param[in] nbytes Number of bytes to decode (pulse must hold nbytes × 8 entries)
292 : : * @note Each bit is classified with the same `<= ONEWIRE_SHORT_PULSE_MAX` rule
293 : : * as onewire_bit_from_pulse(), slot for slot; bit 0 maps to the LSB of
294 : : * its byte. Recovers scratchpad / register bytes from the 1-Wire read
295 : : * capture.
296 : : */
297 : : void onewire_decode_pulses(uint8_t* dst, const volatile uint8_t* pulse, uint8_t nbytes);
298 : :
299 : : /**
300 : : * @brief Encode a byte into write-pulse durations
301 : : * @param[out] out Output buffer (8 entries)
302 : : * @param[in] byte Byte value to encode
303 : : */
304 : : void onewire_encode_byte(ow_pulse_t* out, uint8_t byte);
305 : :
306 : : /**
307 : : * @brief Engage or release the parasite-power strong pull-up on the bus
308 : : * @param[in] on 1 drives the bus line HIGH actively (pin leaves the timer-
309 : : * driven open-drain mode for a push-pull HIGH), 0 releases the
310 : : * line back to the passive external pull-up
311 : : * @note Parasite-powered devices source their supply from the bus line and
312 : : * need this active pull-up during energy-intensive phases: the whole
313 : : * temperature conversion (tCONV, up to 750 ms) after Convert T and the
314 : : * EEPROM programming window (tPROG) after Copy Scratchpad / Recall E².
315 : : * Must only be called between hardware operations (bus idle), never
316 : : * while a timed transaction is running.
317 : : */
318 : : void onewire_strong_pullup(uint8_t on);
319 : :
320 : : #if OW_LOW_POWER
321 : : /**
322 : : * @brief Whether the scheduled hardware stage is a long one (WFE eligible)
323 : : * @return 1 while a long stage (> 1 ms: temperature conversion, scratchpad
324 : : * read, EEPROM hold-off) is in flight, 0 otherwise
325 : : * @note Derived from the scheduled timer duration, so callers stay on the
326 : : * onewire API. Only meaningful with
327 : : * OW_LOW_POWER=1.
328 : : * @note Bus-layer vocabulary, for a slave driver that would rather idle the
329 : : * core than spin on a long stage: the bundled drivers call it from
330 : : * their poll(). An application never needs it - the driver APIs
331 : : * (ds18b20.h, ds2431.h) are start/poll pairs.
332 : : */
333 : : uint8_t onewire_long_wait_pending(void);
334 : :
335 : : /**
336 : : * @brief Block in WFE until the currently scheduled long stage completes
337 : : * @note Only the timer's own update event wakes the core (SEVONPEND, no ISR,
338 : : * no NVIC vector), so to the caller this is an ordinary synchronous
339 : : * wait. Only meaningful with OW_LOW_POWER=1.
340 : : * @pre A long stage must be in flight - the caller checks
341 : : * onewire_long_wait_pending() first, which is exactly what the bundled
342 : : * drivers do. Called with nothing armed, the call does not return: the
343 : : * sleep waits for the timer's update event, and none is coming.
344 : : * @note The blocking counterpart of onewire_long_wait_pending(), for a slave
345 : : * driver that wants to sleep rather than poll. The bundled drivers
346 : : * call it from their poll(); an application never needs it.
347 : : */
348 : : void onewire_sleep_until_done(void);
349 : : #endif
350 : :
351 : : /** @} */
352 : :
353 : : /**
354 : : * @defgroup ONEWIRE_Search Generic Non-Blocking Search ROM Engine
355 : : * @brief Implements the Maxim Search ROM (0xF0) / Alarm Search (0xEC)
356 : : * algorithm as a polled state machine. The direction bit written at
357 : : * position i determines which devices keep participating at position
358 : : * i+1, so the transaction cannot be batched into one DMA pass; the
359 : : * linear loop is decomposed into states with loop counters kept in the
360 : : * context. Every state performs exactly one hardware-timed operation,
361 : : * and no search stage is long enough to become a low-power wait, so a
362 : : * poll call returns straight away.
363 : : * @{
364 : : */
365 : :
366 : : /** @brief Per-device callback invoked by the search engine */
367 : : typedef uint8_t (*onewire_search_sink_t)(const uint8_t* rom);
368 : :
369 : : /**
370 : : * @brief Start a non-blocking search (Search ROM or Alarm Search)
371 : : * @param[in] sink Callback invoked per found device (may be NULL). A non-zero
372 : : * return value stops the search early.
373 : : * @param[in] max_devices Maximum number of devices to report (0 aborts)
374 : : * @param[in] command Search command byte (0xF0 Search ROM / 0xEC Alarm Search)
375 : : * @param[in] family 1-Wire family code to accept, or 0 to accept every family.
376 : : * Only accepted devices increment the found counter and
377 : : * reach the sink.
378 : : * @note Ignores the call while a search pass is already running. Arbitration
379 : : * of the shared bus/timer against other 1-Wire operations lives in the
380 : : * ds18b20_* layer, not here.
381 : : */
382 : : void onewire_search_start(onewire_search_sink_t sink, uint8_t max_devices,
383 : : uint8_t command, uint8_t family);
384 : :
385 : : /**
386 : : * @brief Advance the non-blocking search by one hardware operation
387 : : * @return 1 when the search is finished, 0 while still running
388 : : */
389 : : uint8_t onewire_search_poll(void);
390 : :
391 : : /**
392 : : * @brief Number of devices found (valid once the search finished)
393 : : * @return Count of found devices
394 : : */
395 : : uint8_t onewire_search_count(void);
396 : :
397 : : /**
398 : : * @brief Check whether a search is currently running
399 : : * @return 1 while the search owns the timer, 0 when it is idle
400 : : */
401 : : uint8_t onewire_search_active(void);
402 : :
403 : : /** @} */
404 : :
405 : : /**
406 : : * @defgroup ONEWIRE_CRC CRC Checksums
407 : : * @{
408 : : */
409 : :
410 : : /**
411 : : * @brief Calculate the Dallas/Maxim 1-Wire CRC-8 over a byte buffer
412 : : * @param[in] data Input buffer
413 : : * @param[in] len Number of bytes to process
414 : : * @return CRC-8 checksum value
415 : : */
416 : : uint8_t onewire_crc8(const uint8_t* data, uint8_t len);
417 : :
418 : : /**
419 : : * @brief Calculate the Maxim 1-Wire CRC-16 over a byte buffer
420 : : * @param[in] data Input buffer
421 : : * @param[in] len Number of bytes to process
422 : : * @return 16-bit CRC remainder (CRC-16/ARC parameters: polynomial 0x8005,
423 : : * reflected 0xA001, initial value 0x0000, no final XOR)
424 : : * @note This is the raw remainder (the value that, appended low-byte-first,
425 : : * drives a re-check to 0). Devices such as the DS2431 transmit the
426 : : * inverted form (~value); the caller complements when comparing against
427 : : * the bytes on the bus.
428 : : */
429 : : uint16_t onewire_crc16(const uint8_t* data, uint8_t len);
430 : :
431 : : /** @} */
432 : :
433 : : #ifdef __cplusplus
434 : : }
435 : : #endif
436 : :
437 : : #endif /* ONEWIRE_H */
|