news 2026/6/10 12:03:56

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/6/10 1:10:32

Z-Image-Turbo降本部署案例:免配置镜像+本地GPU高效运行实战

Z-Image-Turbo降本部署案例&#xff1a;免配置镜像本地GPU高效运行实战 随着AI图像生成技术的快速发展&#xff0c;如何在本地环境中低成本、高效率地部署高性能模型成为开发者和企业关注的核心问题。Z-Image-Turbo 作为一款专注于图像生成速度与质量优化的模型&#xff0c;在…

作者头像 李华
网站建设 2026/5/31 14:36:11

探秘 QZ 5T 抓斗行车起重机电气图纸:从切电阻到空操

QZ 5T 抓斗行车起重机 切电阻&#xff0c;空操&#xff0c;电气电器图纸一套这是调试后的最终版图纸&#xff0c;含CAD图纸&#xff0c;元件清单&#xff0c;供学习参考用&#xff0c;这是电气图纸&#xff0c;没有机械的。最近拿到了一套超有意思的资料——QZ 5T 抓斗行车起重…

作者头像 李华
网站建设 2026/6/7 14:02:43

黑胶唱片转录:经典演出观众反应AI分析实战

黑胶唱片转录&#xff1a;经典演出观众反应AI分析实战 1. 引言 在音乐历史的长河中&#xff0c;黑胶唱片承载了无数经典现场演出的珍贵瞬间。然而&#xff0c;这些模拟介质中的音频信息长期以来仅被用于“听”&#xff0c;而难以进行结构化分析。随着AI语音理解技术的发展&am…

作者头像 李华
网站建设 2026/5/1 0:00:02

小白也能懂的通义千问3-14B:从安装到微调全攻略

小白也能懂的通义千问3-14B&#xff1a;从安装到微调全攻略 1. 引言 1.1 学习目标 本文旨在为初学者提供一份完整的 通义千问 Qwen3-14B 模型使用指南&#xff0c;涵盖从本地环境搭建、一键部署、双模式推理到轻量级微调的全流程。无论你是 AI 新手还是希望快速验证大模型能…

作者头像 李华
网站建设 2026/5/20 4:24:45

基于Simulink的车辆坡度与质量识别模型:扩展卡尔曼滤波的奇妙应用

基于simulink的车辆坡度与质量识别模型&#xff0c;扩展卡尔曼滤波&#xff0c;估计曲线与实际误差合理在车辆动力学研究领域&#xff0c;准确识别车辆的坡度与质量对于提升车辆性能、安全性以及燃油经济性至关重要。今天咱们就来唠唠基于Simulink搭建的车辆坡度与质量识别模型…

作者头像 李华
网站建设 2026/5/20 22:22:41

5分钟部署UI-TARS-desktop:零基础玩转AI智能助手

5分钟部署UI-TARS-desktop&#xff1a;零基础玩转AI智能助手 1. 引言&#xff1a;为什么你需要一个AI驱动的GUI自动化助手&#xff1f; 在当今快节奏的工作环境中&#xff0c;重复性界面操作正悄然吞噬着我们的生产力。从数据录入、文件整理到跨应用信息同步&#xff0c;这些…

作者头像 李华