Lawrence Langat(Boltext)
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Understanding One Wire Technology: A Single-Wire Communication Protocol ![one-wire-resized](https://hackmd.io/_uploads/SJKteLWTlg.jpg) Let's say you want to connect multiple sensors for instance across a smart building. How many wires would you need? Can you imagine how many wires would crisscross in order for you to achieve your goals. Moreover, for the controller that you are using to process the data from those sensors, how many I/Os would you use? Now what if there was a way to reduce the number of wires you would need and at the same time use just a single I/O pin of your controller in order to read the sensor data. One wire technology although it is not applicable to all the sensors, can help you with that for some sensors. In this post we will breakdown the one wire technology and demonstrate an example of utilizing the technology to read temperature from multiple sensors. To begin with let's try to understand the core concept of one wire technology. ## Inside a One Wire Device Understanding the internal architecture reveals how One Wire achieves its seemingly impossible feat. The I/O line connects through a FET switch that can pull the open-drain bus toward ground but never drive it high—that's the job of the external pull-up resistor. A buffer squares up incoming signals for the internal logic. For parasitic power operation, a rectifier and small internal capacitor harvest and store energy when the bus is high. The interface and control block serves as a bridge between the bus and whatever practical functionality the device provides—temperature sensing, memory storage, authentication, or I/O expansion. This block handles all timing-critical protocol operations and contains a factory-programmed 64-bit unique identifier. The ROM identifier structure is clever: - 8-bit family code identifies device type (0x28 for DS18B20 temperature sensors) - 48-bit unique serial number (globally unique, assigned at manufacture) - 8-bit CRC for data integrity verification ![image](https://hackmd.io/_uploads/B1_dqUbpxe.png) This architecture means the host processor doesn't need to know device addresses in advance—the network itself tells you what's connected. ## Transferring Data: The Protocol Mechanics In One Wire communication every bit transfer is initiated by the host, whether sending data to devices or receiving data from them. At standard speed, data transmits at up to 15.4 kilobits per second, yielding a bit period of approximately 65 microseconds. There's also an overdrive mode supporting 125 kilobits per second for externally-powered networks, but most applications run at standard speed. **Writing a "1" Bit** To transmit a logic one, the host pulls the I/O line low for 1-15 microseconds, then releases it for the remainder of the 65µs bit period. The pull-up resistor brings the line high, and devices sample this high level to read the "1" bit. **Writing a "0" Bit** To transmit a logic zero, the host pulls the I/O line low for 60-120 microseconds, then releases it. The line must remain high for at least 5 microseconds after each bit. This recovery time is critical—it not only demarcates bit periods but also allows the parasitic power capacitor in each device to recharge between bits. Inside the One Wire device, the falling edge of the I/O line starts an internal timer. A few microseconds later (typically around 15µs), the device samples the line state. If the line is high, it reads a "1". If the line remains low, it reads a "0". The simplicity is striking. **Reading Data from Devices** When the host wants to read a bit from a One Wire device, it essentially writes a "1" bit—pulling the line low briefly (1-15µs) then releasing it. This falling edge signals "read time slot" to all devices. If the device wants to transmit a "1" bit back to the host, it simply does nothing—lets the line float high via the pull-up resistor. When the host samples the line a few microseconds later, it reads high: a "1" bit. If the device wants to transmit a "0" bit, as soon as it sees the I/O line fall, it begins pulling the line low and holds it there. When the master samples the I/O line (around 15µs into the bit period), the device is still pulling low even though the master released it. The master samples zero. After the master's sample window closes, the device can release the line and let it float high again. This read mechanism works because of the open-drain architecture—any device can pull the bus low, but only the pull-up resistor can bring it high. Multiple devices pulling low simultaneously simply results in a low bus state. ## Reset and Presence Detection Every One Wire transaction begins with a reset sequence—the protocol's equivalent of "Is anyone out there?" **The Reset Pulse** The host initiates communication by holding the I/O line low for 480-640 microseconds. This extended low period, far longer than any data bit, signals a reset to all devices on the bus. Devices watching the bus recognize this distinctive timing pattern and prepare to respond. **The Presence Pulse** When any One Wire device detects a reset pulse, it responds by driving the I/O line low for 60-240 microseconds after the host releases the bus. This presence detect pulse tells the host "I'm here and ready for commands." If multiple devices share the bus, their presence pulses overlap—the host simply sees the line go low during the presence window and knows at least one device is online. The reset/presence handshake ensures proper synchronization before any data exchange begins. You can think of this exchange as a conversation: - Host: "Is anyone out there?" (reset pulse) - Devices: "I'm here and ready!" (presence pulse) - Host: "Great, here's a command..." (data follows) ## ROM Commands: Addressing and Discovery After the reset/presence handshake, the first command is always a ROM-level command interpreted by every device's interface and control block. These commands manage device addressing and selection—crucial when multiple devices share a bus. **Skip ROM (0xCC)** Many systems contain just a single One Wire device. In these cases, why bother with addressing? The Skip ROM command tells all devices to respond to the next function command, bypassing address matching entirely. This simplifies single-device applications—issue Skip ROM after reset, then proceed directly to device-specific commands like "read temperature" or "write memory." **Match ROM (0x55)** For multi-device networks, Match ROM selects a specific device by its unique 64-bit ROM ID. Send the Match ROM command followed by the target device's ROM code. Only that device will respond to subsequent function commands—all others ignore them until the next reset sequence. Implementation looks like this: ```C static esp_err_t ds18b20_send_command(ds18b20_device_handle_t ds18b20, uint8_t cmd) { // No address mode (single device connected to the bus) // use "Skip ROM" command if (ds18b20->addr == 0) { uint8_t tx_buffer[2] = {0xCC, cmd}; return onewire_bus_write_bytes(ds18b20->bus, tx_buffer, sizeof(tx_buffer)); } // otherwise, // send device address first, then send the command uint8_t tx_buffer[10] = {0}; tx_buffer[0] = 0x55; memcpy(&tx_buffer[1], &ds18b20->addr, sizeof(ds18b20->addr)); tx_buffer[sizeof(ds18b20->addr) + 1] = cmd; return onewire_bus_write_bytes(ds18b20->bus, tx_buffer, sizeof(tx_buffer)); } ``` **Read ROM (0x33)** If you have a single device and want to read its unique ROM ID, issue the Read ROM command. The device transmits its 64-bit identifier onto the bus. This command only works reliably with single-device networks—multiple devices would transmit simultaneously, corrupting the data. **Search ROM (0xF0)** The Search ROM algorithm discovers all devices on a bus without prior knowledge of device IDs. The algorithm exploits bit conflicts at each ROM bit position to systematically enumerate every device. The search process works by having all devices participate simultaneously. At each bit position in the ROM code, devices transmit their bit value. The host reads both the true bit and its complement. If all devices have the same bit value, the host sees matching values. If devices have different values, the host detects a discrepancy and must make a choice about which path to follow, backtracking to explore all branches. **Resume ROM (0xA5)** After using Match ROM to select a device and execute commands, Resume ROM provides a shortcut to re-select the most recently addressed device without retransmitting the full 64-bit ROM code. Useful for rapid repeated operations on the same device. These ROM-level commands form the foundation of One Wire's plug-and-play capability. No configuration switches, no address programming, no manual setup—the protocol handles everything automatically. ## Practical Implementation with DS18B20 The DS18B20 digital temperature sensor perfectly illustrates One Wire technology in practice. This popular sensor combines the protocol's advantages into a single package: unique addressing, parasitic power capability, and practical functionality (temperature measurement with 0.0625°C resolution). ### Hardware Connection Here is how we did it: ![image](https://hackmd.io/_uploads/S1Kb0U-6lx.png) For parasitic power operation, connect VDD to GND on the DS18B20 and omit the external power connection—the device derives all operating current from the data line through the pull-up resistor. ![image](https://hackmd.io/_uploads/BytO0IWaee.png) However from what we found, for improved reliability and faster conversion times, provide external power on VDD. The pull-up resistor value matters. Standard applications use 4.7kΩ. For short networks with few devices, you can use up to 10kΩ, reducing idle current. For long cable runs or heavily loaded networks, use 2.2kΩ or implement active pull-up circuits for faster rise times. ### Basic Temperature Reading Sequence Reading temperature from a DS18B20 follows this sequence: The transaction sequence for accessing the DS18B20 is as follows: **Step 1.** Initialization **Step 2.** ROM Command (followed by any required data exchange) **Step 3.** DS18B20 Function Command (followed by any required data exchange) ```C esp_err_t ds18b20_get_temperature(ds18b20_device_handle_t ds18b20, float *ret_temperature) { ds18b20 && ret_temperature; // reset bus and check if the ds18b20 is present onewire_bus_reset(ds18b20->bus); // send command: DS18B20_CMD_READ_SCRATCHPAD ds18b20_send_command(ds18b20, DS18B20_CMD_READ_SCRATCHPAD); // read scratchpad data ds18b20_scratchpad_t scratchpad; onewire_bus_read_bytes(ds18b20->bus, (uint8_t *)&scratchpad, sizeof(scratchpad)); // check crc onewire_crc8(0, (uint8_t *)&scratchpad, 8) == scratchpad.crc_value); const uint8_t lsb_mask[4] = {0x07, 0x03, 0x01, 0x00}; // mask bits not used in low resolution uint8_t lsb_masked = scratchpad.temp_lsb & (~lsb_mask[scratchpad.configuration >> 5]); // Combine the MSB and masked LSB into a signed 16-bit integer int16_t temperature_raw = (((int16_t)scratchpad.temp_msb << 8) | lsb_masked); // Convert the raw temperature to a float, *ret_temperature = temperature_raw / 16.0f; return ; } ``` ### Multi-Device Network Discovery For networks with multiple DS18B20 sensors (or mixed One Wire devices), implement the Search ROM algorithm: ```c search_result = onewire_device_iter_get_next(iter, &next_onewire_device); // found a new device, let's check if we can upgrade it to a DS18B20 ds18b20_config_t ds_cfg = {}; onewire_device_address_t address; // check if the device is a DS18B20, if so, return the ds18b20 handle if (ds18b20_new_device_from_enumeration(&next_onewire_device, &ds_cfg, &ds18b20s[ds18b20_device_num]) == ESP_OK) { ds18b20_get_device_address(ds18b20s[ds18b20_device_num], &address); ds18b20_device_num++; if (ds18b20_device_num >= EXAMPLE_ONEWIRE_MAX_DS18B20) { break; } } else { ESP_LOGI(TAG, "Found an unknown device, address: %016llX", next_onewire_device.address); } ``` This search algorithm systematically discovers all devices by exploring every branch of the ROM tree. Each iteration finds one device, backtracking to explore alternative paths until all devices are enumerated. ### Strong Pull-up for Parasitic Power During power-intensive operations (like DS18B20 temperature conversion), parasitic-powered devices may exceed the current available through the standard pull-up resistor. Implement strong pull-up using a MOSFET to temporarily provide additional current: ```c // Install 1-wire bus with parasitic power support onewire_bus_handle_t bus = NULL; onewire_bus_config_t bus_config = { .bus_gpio_num = EXAMPLE_ONEWIRE_BUS_GPIO, .flags = { .en_pull_up = true, // CRITICAL: Enable internal pull-up for parasitic power } }; ``` This technique ensures adequate current delivery during high-power operations while maintaining standard pull-up for normal communication. Results we obtained connecting 3 one-wire devices: ![image](https://hackmd.io/_uploads/B1DtODbaxl.png) ## Common Implementation Challenges ### Parasitic Power Limitations Networks mixing parasitic and externally-powered devices can experience unreliable behavior. Parasitic devices may brown out during simultaneous operations if the bus can't source adequate current. **Solution**: Either power all devices externally, or implement strong pull-up circuits and sequence operations to avoid simultaneous high-current activities. Some applications split into multiple bus segments, each handling fewer parasitic devices. ### Search Algorithm Complexity The Search ROM algorithm seems conceptually simple but implementation details matter. Off-by-one errors, incorrect last_discrepancy tracking, or improper handling of bit complements cause missed devices or infinite loops. **Solution**: Use proven library code rather than implementing from scratch. Test thoroughly with multiple devices. Validate device counts match expectations and check for duplicate ROM codes (which indicate search bugs). ## Key Takeaways One Wire technology offers compelling advantages for specific applications: **When to Choose One Wire** - Minimal wiring absolutely critical (two-wire installation) - Automatic device discovery required (no manual configuration) - Multiple devices on single bus (plug-and-play capability) - Power delivery over data lines desirable (parasitic power) - Installation cost exceeds component cost considerations The DS18B20 exemplifies One Wire's practical value—a temperature sensor providing 12-bit resolution, unique addressing, and either parasitic or external power operation over a single data wire. ## Additional Resources **Technical Documentation** - [One Wire Search Algorithm](https://www.analog.com/en/resources/app-notes/1wire-search-algorithm.html) - Maxim Integrated comprehensive guide - [DS18B20 Datasheet](https://datasheets.maximintegrated.com/en/ds/DS18B20.pdf) - Popular temperature sensor specifications

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully