教你如何简单测温(DS18B20)

使用DS18B20温度传感器进行测温
好处:测量简便精准,成本低。

思路: 根据手册要求先定义初始化函数,写函数,读函数。再根据相应格式写出主函数,求出温度值,最后用显示函数将温度显示在数码管上,保留一位小数。

#include<reg52.h>
#include<intrins.h>
typedef unsigned int uint;
typedef unsigned char uchar;
sbit DS=P2^2;
sbit du=P2^6;
sbit we=P2^7;

uchar code SMGdu[] = {0x3f,0x06,0x5b,0x4f,0x66,
				0x6d,0x7d,0x07,0x7f,0x6f};
uchar code SMGwe[] = {0xfe,0xfd,0xfb};
void delayus(uint i)  //执行一次语句17us
{
	while(i--);	 //i减一次10us
}
void delay(uint z)
{
	uint x,y;
	for(x=z;x>0;x--)
		for(y=114;y>0;y--);
}
void display(uint k)
{
	du=0;
	P0=SMGdu[k/100];
	du=1;
	du=0;

	we=0;
	P0=SMGwe[0];
	we=1;
	we=0;
	delay(1);

	du=0;
	P0=SMGdu[k/10%10]|0x80;
	du=1;
	du=0;

	we=0;
	P0=SMGwe[1];
	we=1;
	we=0;
	delay(1);

	du=0;
	P0=SMGdu[k%10];
	du=1;
	du=0;

	we=0;
	P0=SMGwe[2];
	we=1;
	we=0;
	delay(1);
}
//初始化
bit DS_Init()
{
	bit i;
	DS=1;
	_nop_();
	DS=0;
	delayus(48);//497us;
	DS=1;
	delayus(2);//37us
	i=DS;
	delayus(15);//167us
	DS=1;
	_nop_();
	return i;
}
//写一个字节指令
void write_byte(uchar dat)
{
	uchar i;
	for(i=0;i<8;i++)
	{
		DS=0;
		_nop_();
		DS=dat&0x01;
		delayus(8);//97us
		DS=1;
		_nop_();
		dat>>=1;
	}
}
//读一个字节
uchar read_byte()
{
	uint i,j;
	uchar dat;
	for(i=0;i<8;i++)
	{
		DS=0;
		_nop_();
		DS=1;
		_nop_();
		j=DS;
		delayus(6);//77us
		DS=1;
		_nop_();
		dat=(j<<7)|(dat>>1);
	}
	return dat;	
}
void main()
{
	uint S;
	uchar H,L;
	while(1)
	{
		DS_Init();
		write_byte(0xcc);
		write_byte(0x44);

		DS_Init();
		write_byte(0xcc);
		write_byte(0xBE);

		L=read_byte();
		H=read_byte();

		S=H;
		S<<=8;
		S|=L;
		S=S*0.0625*10+0.5;
		display(S);
		
	}
}
  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

月牙 ,呐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值