单片机控制DS18B20自制简易电子温度计(测试通过)(一)

花了一天多时间弄电子温度计,关键问题还是出现在延时不准确,导致不能正常工作。没有严格按照时序中要求的时序,也让我吃了不少苦头。在这里,简单向大家介绍下常用的温度芯片DS18B20。

一、硬件部分

1>引脚

                                                                                  

这是常用的DS18b20温度芯片,有引脚三根。

GND:地点

VD:电源线

DQ:数据线

DS18B20使用的一线接口控制,当没有外部电源时,这根线同时作为芯片电源线,也就是寄生电源,在本篇中仅就使用外部电源且总线只挂1个DS18B20进行说明。

2>温度数据存储格式

                                               

对应的温度表如下:

                            

从图可知,温度高字节的高5位是表示正负的,全0为正,全1为负。

****************************************************************************************************************

详情请咨询:                                                 http://shop108408772.taobao.com/

*********************************************************

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个基于C51简易温度计设计代码,使用的传感器为DS18B20: ```c #include<reg51.h> typedef unsigned char uchar; typedef unsigned int uint; sbit DQ=P3^7; // DS18B20 数据线 uchar code table[] = {0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f}; // 数码管显示表 void Delay10us() // 延时10微秒 { uchar i; for (i=0; i<2; i++); } void Delay500us() // 延时500微秒 { uchar i,j; for (i=15; i>0; i--) for (j=20; j>0; j--); } void DelayMs(uchar ms) // 延时ms毫秒 { uchar i,j; while (ms--) { for (i=2; i>0; i--) for (j=245; j>0; j--); } } void WriteDs18b20(uchar dat) // 写入一个字节 { uchar i; for (i=0; i<8; i++) { DQ = 0; Delay10us(); DQ = dat & 0x01; dat >>= 1; Delay10us(); DQ = 1; } } uchar ReadDs18b20() // 读取一个字节 { uchar i, dat = 0; for (i=0; i<8; i++) { DQ = 0; Delay10us(); DQ = 1; Delay10us(); dat |= DQ << i; } return dat; } void Convert() // 启动温度转换 { DQ = 1; Delay10us(); DQ = 0; Delay500us(); DQ = 1; Delay10us(); } void InitDs18b20() // 初始化DS18B20 { DQ = 1; Delay10us(); DQ = 0; Delay500us(); DQ = 1; Delay10us(); } uint GetTemp() // 读取温度 { uchar temp[2]; uint temperature; InitDs18b20(); Convert(); InitDs18b20(); WriteDs18b20(0xcc); // 跳过ROM操作 WriteDs18b20(0xbe); // 读取温度 temp[0] = ReadDs18b20(); // 低8位 temp[1] = ReadDs18b20(); // 高8位 temperature = temp[1]; temperature <<= 8; temperature |= temp[0]; temperature >>= 4; return temperature; } void Display(uint temp) // 数码管显示温度 { uchar i, j; uchar code array[] = {0xfe,0xfd,0xfb,0xf7}; // 位选 uchar th, tl; th = temp >> 4; tl = temp & 0x0f; for (i=0; i<4; i++) { P2 = array[i]; if (i == 2) P0 = 0x80; // 小数点 else P0 = table[th]; DelayMs(1); P0 = 0x00; } P2 = 0xff; for (j=0; j<20; j++) // 20ms闪烁一次 { P0 = table[tl]; DelayMs(1); P0 = 0x00; DelayMs(9); } } void main() { uint temp; while (1) { temp = GetTemp(); // 读取温度 Display(temp); // 数码管显示温度 } } ``` 注意:该代码仅供参考,具体实现可能还需要根据具体硬件情况进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值