news 2026/4/16 22:57:02

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/4/13 20:14:54

Carsim与Simulink联合仿真实现变道:探索弯道中的智能驾驶奥秘

carsimsimulink联合仿真实现变道 包含路径规划算法mpc轨迹跟踪算法 可选simulink版本和c版本算法 可以适用于弯道道路&#xff0c;弯道车道保持&#xff0c;弯道变道 carsim内规划轨迹可视化 Carsim2020.0 Matlab2017b在智能驾驶领域&#xff0c;车辆的路径规划与轨迹跟踪是核心…

作者头像 李华
网站建设 2026/4/4 18:01:22

用预置镜像在RTX 4090D上快速完成Qwen2.5-7B微调实战

用预置镜像在RTX 4090D上快速完成Qwen2.5-7B微调实战 1. 引言 大模型微调正从“高门槛实验”走向“轻量化落地”。对于开发者而言&#xff0c;如何在有限时间内高效完成一次高质量的模型定制&#xff0c;已成为实际业务中的关键需求。以 Qwen2.5-7B 这类中等规模的大语言模型…

作者头像 李华
网站建设 2026/4/16 0:10:38

阿里通义Z-Image-Turbo应用场景:广告创意视觉AI辅助生成

阿里通义Z-Image-Turbo应用场景&#xff1a;广告创意视觉AI辅助生成 1. 引言 1.1 广告创意生产的效率瓶颈 在数字营销时代&#xff0c;广告素材的生产速度与多样性直接决定投放效果。传统设计流程依赖人工构思、绘图、修图等多个环节&#xff0c;单张高质量视觉图往往需要数…

作者头像 李华
网站建设 2026/3/28 4:51:38

零基础掌握配置文件在初始化中的应用

配置文件&#xff1a;让嵌入式系统“活”起来的关键设计你有没有遇到过这样的场景&#xff1f;一款数字功放产品刚交付客户&#xff0c;现场工程师反馈&#xff1a;“能不能把启动音量调低一点&#xff1f;”、“采样率改成44.1k试试&#xff1f;”——结果你只能苦笑&#xff…

作者头像 李华
网站建设 2026/3/31 6:32:57

乐迪信息:智能识别船舶种类的AI解决方案

无论是港口的日常运营、海上交通安全监管&#xff0c;还是海洋资源的合理调配&#xff0c;都需要对过往船舶进行快速且精准的分类识别。传统的船舶识别方式主要依赖人工观察与经验判断&#xff0c;这种方式不仅效率低下&#xff0c;而且容易受到诸多因素的干扰&#xff0c;如恶…

作者头像 李华
网站建设 2026/4/16 15:22:05

端到端人像转卡通方案落地|利用DCT-Net GPU镜像省时提效

端到端人像转卡通方案落地&#xff5c;利用DCT-Net GPU镜像省时提效 在AI图像生成技术迅猛发展的今天&#xff0c;虚拟形象、二次元头像、个性化卡通化表达已成为社交平台、数字人设和内容创作的重要组成部分。然而&#xff0c;传统的人像风格迁移方法往往面临模型部署复杂、显…

作者头像 李华