news 2026/5/12 1:00:16

DAY49 DS18B20 Single-Wire Digital Temperature Acquisition

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
DAY49 DS18B20 Single-Wire Digital Temperature Acquisition

DS18B20 Single-Wire Digital Temperature Acquisition

I. DS18B20 Core Features & Hardware Basics

1. Key Parameters (Must Remember!)

ParameterSpecifications
Measurement Range-55℃ ~ +125℃ (Full industrial coverage)
Accuracy±0.5℃ within -10℃~+85℃, ≤±2℃ full range
ResolutionAdjustable 9~12 bits (default 12-bit): 9-bit=0.5℃, 10-bit=0.25℃, 11-bit=0.125℃, 12-bit=0.0625℃
Operating Voltage3V~5.5V (Compatible with 51 MCU 3.3V/5V power, no extra regulator needed)
Communication InterfaceSingle-wire GPIO bus (Only 1 I/O pin + GND, extremely low hardware cost)
Core AdvantagesNo external components, strong anti-interference, supports multi-sensor networking, retains configuration during power loss

2. Pin Definitions & Wiring

DS18B20 uses TO-92 package with 3 pins. 51 MCU wiring:

DS18B20 PinFunction51 MCU Connection
VDDPower pinConnect to 3.3V/5V (external power mode) or leave floating (parasitic power mode)
DQData I/OConnect to any GPIO (code uses P3.7) + 4.7KΩ pull-up resistor
GNDGroundConnect to MCU GND (must share ground to prevent signal interference)

Critical Note: Single-wire bus must have 4.7KΩ pull-up resistor to ensure high level when idle for stable communication.


II. DS18B20 Core Timing Principles (Communication Key!)

DS18B20 communication relies on strict timing protocols. All operations (reset, write, read) must follow single-wire bus timing rules - the core of successful acquisition.

1. Reset Timing (Initialization)

All communication starts with reset:

  1. Host (51 MCU) pulls bus low≥480μs(reset pulse);
  2. Host releases bus, switches to input mode after pulling high;
  3. DS18B20 detects rising edge, delays 15~60μs, then pulls bus low60~240μs(presence pulse) to signal “ready”;
  4. DS18B20 releases bus, returns to high level, enters idle state.

Code implementation:ds18b20_reset()usesDelay10us(70)for 700μs reset,Delay10us(6)to wait for presence pulse.

2. Write Timing (Host→DS18B20)

Host sends “0” or “1” via different low-level durations (LSB first, 8 bits = 1 byte):

  • Write 0: Pull bus low≥60μs→ release (pull high); DS18B20 samples within 60μs, low level = “0”;
  • Write 1: Pull bus low1~15μs→ release (pull high); DS18B20 samples high level = “1”;
  • Minimum 1μs recovery between writes.

Code implementation:write_ds18b20()usesdat&1to determine bit, short delay for 1, long delay for 0.

3. Read Timing (DS18B20→Host)

Host triggers read by pulling bus low, then DS18B20 controls bus level:

  1. Host pulls bus low≥1μs→ immediately releases (pull high);
  2. Host samples bus level within 15μs (high=1, low=0);
  3. Single read duration ≥60μs, minimum 1μs between reads.

Code implementation:read_ds18b20()pulls low then quickly releases, detects level viaDQ_CHECK, stores indat.


III. Core Command Analysis (DS18B20 Operation Soul)

DS18B20 executes operations based on 8-bit host commands. Code uses 3 core commands:

Command ByteCommand NameFunction
0xCCSkip ROMBypasses reading DS18B20’s 64-bit ROM code (preferred for single-sensor scenarios)
0x44Convert TInitiates temperature conversion (12-bit takes ~750ms), bus must stay high during conversion
0xBERead ScratchpadReads DS18B20’s 9-byte scratchpad (first 2 bytes contain temperature data)

Extension: Multi-sensor networks require0x55(Match ROM) + 64-bit ROM code to target specific sensors.


IV. Complete 51 MCU Code Analysis

Code implements “Reset → Measure → Read → Data Processing” via P3.7 pin, ready for compilation.

1. Header & Macros (ds18b20.h)

#ifndef__DS18B20_H__#define__DS18B20_H__#include<reg51.h>// Function declarationsintds18b20_reset(void);// Reset DS18B20voidwrite_ds18b20(unsignedchardat);// Write 1 byte to DS18B20unsignedcharread_ds18b20(void);// Read 1 byte from DS18B20floatget_temp(void);// Get temperature (returns float)#endif

2. Core Function Implementation (ds18b20.c)

#include<reg51.h>#include<intrins.h>#include"ds18b20.h"#include"delay.h"// Macro definitions: P3.7 as DQ pin#defineDQ_DOWN(P3&=~(1<<7))// Pull DQ low#defineDQ_HIGH(P3|=(1<<7))// Pull DQ high#defineDQ_CHECK((P3&(1<<7))!=0)// Check DQ level/** * @brief DS18B20 reset initialization * @retval 1-Reset successful, 0-Reset failed */intds18b20_reset(void){intt=0;// 1. Send reset pulse (pull low ≥480μs)DQ_DOWN;Delay10us(70);// 70×10μs=700μs, meeting ≥480μs requirementDQ_HIGH;// Release the busDelay10us(6);// Wait 60μs to receive presence pulse// 2. Detect presence pulse (DS18B20 pulls bus low)while(DQ_CHECK&&t<30)// Timeout 300μs if no low level detected → failure{Delay10us(1);t++;}if(t>=30)return0;// Reset failed// 3. Wait for presence pulse to end (DS18B20 pulls bus high)t=0;while(!DQ_CHECK&&t<30)// Timeout 300μs if not pulled high → failure{Delay10us(1);t++;}if(t>=30)return0;// Reset failedreturn1;// Reset successful}/** * @brief Write 1 byte to DS18B20 (LSB first) * @param dat: Byte to send */voidwrite_ds18b20(unsignedchardat){inti=0;for(i=0;i<8;i++)// Loop 8 times, writing 1 bit each time{if(dat&1)// Write 1: Pull low for 1~15μs{DQ_DOWN;_nop_();// Short delay (~1μs)_nop_();DQ_HIGH;// Release the busDelay10us(5);// Wait 45μs to ensure DS18B20 sampling}else// Write 0: Pull low ≥60μs{DQ_DOWN;Delay10us(6);// 60μsDQ_HIGH;// Release the bus}dat>>=1;// Right shift 1 bit, preparing to write next bit (LSB first)}}/** * @brief Read 1 byte from DS18B20 (LSB first) * @retval Byte read */unsignedcharread_ds18b20(void){unsignedchardat=0;inti=0;for(i=0;i<8;i++)// Loop 8 times, reading 1 bit each time{DQ_DOWN;// Pull low ≥1μs to trigger read operation_nop_();_nop_();DQ_HIGH;// Release the bus, letting DS18B20 control the level_nop_();_nop_();_nop_();// Delay ~3μs, preparing to sampleif(DQ_CHECK)// Sample level: high=1, low=0{dat|=(1<<i);// Store corresponding bit (LSB first)}Delay10us(6);// Single read operation ≥60μs}returndat;}/** * @brief Get temperature value * @retval Float temperature (precision 0.0625℃) */floatget_temp(void){unsignedchartl=0;// Temperature low byte (LSB)unsignedcharth=0;// Temperature high byte (MSB, including sign bit)shortt=0;// Combined 16-bit temperature data// 1. Reset→Skip ROM→Start temperature conversionif(ds18b20_reset()==0)return-99.9;// Return error value if reset failswrite_ds18b20(0xCC);// Skip ROM (single sensor)write_ds18b20(0x44);// Start temperature conversionDelay1ms(1000);// Wait for conversion to complete (≥750ms for 12-bit resolution)// 2. Reset→Skip ROM→Read scratchpadds18b20_reset();write_ds18b20(0xCC);// Skip ROMwrite_ds18b20(0xBE);// Read scratchpad// 3. Read temperature data (first 2 bytes are temperature value, LSB first)tl=read_ds18b20();// Low byteth=read_ds18b20();// High byte// 4. Combine temperature data (16-bit signed two's complement)t=th<<8;// High byte left shift 8 bitst|=tl;// Combine low byte// 5. Temperature conversion: 12-bit resolution→1LSB=0.0625℃returnt*0.0625;}

3. Delay Function Support (delay.c/h)

DS18B20 timing requires high-precision delays (10μs, 1ms level with 11.0592MHz crystal):

// delay.h#ifndef__DELAY_H__#define__DELAY_H__voidDelay10us(unsignedintn);voidDelay1ms(unsignedintn);#endif// delay.c#include<reg51.h>voidDelay10us(unsignedintn){unsignedinti,j;for(i=n;i>0;i--)for(j=2;j>0;j--);// ≈10μs at 11.0592MHz}voidDelay1ms(unsignedintn){unsignedinti,j;for(i=n;i>0;i--)for(j=110;j>0;j--);// ≈1ms at 11.0592MHz}

4. Main Function Call Example (main.c)

#include<reg51.h>#include"ds18b20.h"#include"uart.h"// Assuming UART send functions are implementedvoidmain(void){floattemp;uart_init();// Initialize UART (for printing temperature)while(1){temp=get_temp();// Get temperatureif(temp!=-99.9)// Successful acquisition{// UART print temperature (floating-point to string function omitted here)uart_sendstr("Current temperature: ");// Example: Print integer part + decimal part}Delay1ms(2000);// Sample every 2 seconds}}

5. Key Practical Considerations

  1. Pull-up resistor is essential: A 4.7KΩ pull-up resistor is critical for stable single-wire bus communication; its absence can cause reset failures or data errors.
  2. Delay precision must meet requirements: Timing parameters (e.g., 480μs reset, 60μs write 0) must strictly match; excessive delay errors will cause acquisition failures.
  3. Wait for temperature conversion: After issuing the conversion command (0x44), sufficient time must be allowed (≥750ms for 12-bit resolution); otherwise, old data will be read.
  4. Parasitic power mode note: If DS18B20 uses parasitic power (VDD floating), the bus must remain high during conversion, and no other operations should be performed.
  5. Multi-sensor networking: Use0x55(Match ROM) command + sensor’s unique 64-bit ROM code to avoid data conflicts.

6. Temperature Data Parsing Principle

DS18B20 stores temperature data as 16-bit signed two’s complement:

Bit 15 (MSB)Bits 14-11Bits 10-4Bits 3-0 (LSB)
Sign bit (0=positive, 1=negative)Integer partFractional partFractional part (12-bit resolution)
  • Positive numbers: Directly convert using “integer part × 1 + fractional part × 0.0625”.
  • Negative numbers: Convert using two’s complement rules (invert + 1) before calculation, with negative sign.
  • Example: 25.5℃ → Binary00000000 00011001.1000→ Hex0x00198→ Convert to 25 + 8×0.0625=25.5℃.

Summary

DS18B20’s core advantages are “single-wire communication + minimal hardware”. Key learning focuses ontiming protocolandcommand parsing: Reset is the communication prerequisite, write/read timing forms the data transmission foundation, and temperature conversion/scratchpad read commands are core operations. Mastering the code and principles here enables easy expansion to multi-sensor networks, temperature alarms (using TH/TL registers), UART temperature uploads, etc., making it suitable for embedded applications like environmental monitoring and equipment temperature control.

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/5/11 10:54:05

最近在折腾移动机器人路径规划,发现传统A星+DWA组合在实际场景里经常拉胯。全局路径折线感太强,局部避障又容易跟丢全局路线,今天咱们聊聊几个接地气的优化姿势

改进A星算法dwa先看传统A星生成的路径&#xff0c;直角转弯看着就难受。加个路径后处理能救&#xff1a; # Floyd路径平滑 def floyd_smooth(path, obstacle_map):new_path [path[0]]for i in range(len(path)-2):# 尝试连接非连续节点if not line_has_collision(new_path[-1]…

作者头像 李华
网站建设 2026/5/11 10:53:38

低功耗显示方案:ST7789V在穿戴设备中的应用

低功耗显示方案&#xff1a;ST7789V在穿戴设备中的实战解析 你有没有遇到过这样的情况&#xff1f;花了不少钱买的智能手环&#xff0c;功能齐全、设计精美&#xff0c;但 一到下午就得充电 。抬腕看个时间&#xff0c;屏幕刚亮起几秒就暗了——这背后&#xff0c;很可能不是…

作者头像 李华
网站建设 2026/5/11 8:16:34

工业通信协议配置前的STM32CubeMX下载指导

从零开始搭建工业通信系统&#xff1a;STM32CubeMX 配置实战指南 在现代工业自动化现场&#xff0c;工程师常常面临这样的挑战&#xff1a;如何快速、稳定地让一颗 STM32 芯片“活”起来&#xff0c;并准备好与 Modbus、CAN 或以太网设备对话&#xff1f;不是靠手敲寄存器&…

作者头像 李华
网站建设 2026/5/11 0:07:06

当COBACABANA注入AI灵魂:智能工厂动态调度系统从0到1落地实战

一、AI时代的生产调度困局&#xff1a;为何85%的制造企业陷入"系统失灵"魔咒&#xff1f;2023年中国制造业数字化转型调研报告显示&#xff0c;85%的制造企业在引入智能生产管理系统&#xff08;MES/APS&#xff09;后&#xff0c;依然面临"计划赶不上变化&…

作者头像 李华
网站建设 2026/5/9 18:07:31

FST ITN-ZH教程:中文文本标准化错误恢复机制

FST ITN-ZH教程&#xff1a;中文文本标准化错误恢复机制 1. 简介与背景 中文逆文本标准化&#xff08;Inverse Text Normalization, ITN&#xff09;是语音识别系统中不可或缺的一环。在自动语音识别&#xff08;ASR&#xff09;输出的文本通常包含大量口语化、非标准表达&am…

作者头像 李华
网站建设 2026/5/11 10:17:16

科研党必备PDF提取神器|PDF-Extract-Kit实现公式表格一键转换

科研党必备PDF提取神器&#xff5c;PDF-Extract-Kit实现公式表格一键转换 1. 引言&#xff1a;科研文档处理的痛点与解决方案 在科研工作中&#xff0c;PDF文档是知识传递的核心载体。然而&#xff0c;从学术论文中提取公式、表格和文本内容往往是一项耗时且容易出错的任务。…

作者头像 李华