51(52)单片机 DS18B20温度传感器与数码管的综合运用

单片机小白

DS18B20温度传感器的数据经过处理显示在数码管上

运行效果:

在这里插入图片描述

代码:

#include <reg52.h>
#include <intrins.h>


typedef unsigned char u8;
typedef unsigned int u16;
typedef signed int s16;
 
   sbit IO_18B20=P3^7;

   sbit add_1=P2^2;
   sbit add_2=P2^3;
   sbit add_3=P2^4;



   u8 DQ;
   u8 c[8];
   u8 code a[10]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};//0-9

	 

void Delay_ms(unsigned char ms)//定时器延时函数
  {
    unsigned char T=0;
    TMOD=0x01;
    TH0=0xfb;
    TL0=0x80;
    TR0=1;
    while(T<ms)
    {
     if(TF0==1)
	   {
	    TF0=0;
	  	TH0=0xfb2 ;
      TL0=0x80;
		  T++;
	   }
    }
    
  }//1.25*ms
	


void Delay(u16 i)//延时
{
	while(i--);	
}



void init_18B20()//DS18B20初始化
{
	IO_18B20=0;
	Delay(100);        
	IO_18B20=1;
	Delay(5);  
	DQ=IO_18B20;
	Delay(80);         
	
}

void write_cmd(u8 cmd)//DS18B20写时序
{
	u8 i;
	for(i=0;i<8;i++)
	{
	  IO_18B20=0;
  	  _nop_();         
	  IO_18B20=cmd&0x01;
  	  Delay(6);         
  	  IO_18B20=1;
      cmd>>=1;
  }

}


u8 read_cmd()//DS18B20读时序
{
	u8 j,by,byte;
	for(j=0;j<8;j++)
	{
	  IO_18B20=0;
  	  _nop_();         
	  IO_18B20=1;
	  _nop_();  
	  _nop_();      
	  by=IO_18B20;
	  byte=(byte>>1)|(by<<7);
  	  Delay(4);         
  }
	return byte;

}


void change_temper()//温度转换
{

	init_18B20();
	if(DQ==0)
	 {
	   write_cmd(0xcc);//跳过ROM
	   write_cmd(0x44);//温度转换后存储在暂存寄存器的2个字节长度的温度寄存器中
	 }
	 
}



void read_temper()//读温度
{
	 init_18B20();
	 if(DQ==0)
	  {
	    write_cmd(0xcc);//跳过ROM
		write_cmd(0xbe);//读取暂存寄存器
	  }
}


s16 DS18B20temp_data()//采集DS18B20中cache温度数据
{
	s16 temp;
	u8 temph,templ;
	change_temper();
	read_temper();
	templ=read_cmd();
	temph=read_cmd();
	temp=temph;
	temp<<=8;
	temp|=templ;
	return temp;

}

void datapros(s16 temp)//将采集的数据按照规定的分辨率转化为数字
{
	float tp;
	if(temp<0)
	 { 
	
		 c[0]=0x40;
		 temp=~temp;
		 temp+=1;
		 tp=temp;
		 temp=tp*0.0625*100+0.5;
	 }
	 else
	 {
	    c[0]=0x00;
	    tp=temp;
		temp=tp*0.0625*100+0.5;   //0.0625为分辨率   100:保留两位小数  0.5:精度
	 }
	c[1] = a[temp/1000%10];//显示温度十位
	c[2] = a[temp/100%10]+0x80;//显示温度个位
	c[3] = a[temp/10%10];//显示一位小数


}	


void shuaxin()//刷新数码管
 {
	 add_1=0;
     add_2=0;
     add_3=0;
	 P0=0x39;   //数码管显示  C
	Delay_ms(1);	
	 P0=0x00;
			
	 add_1=1;
	 add_2=0;
	 add_3=0;
     P0=c[3];
   Delay_ms(1);	
	 P0=0x00;
	 
	 add_1=0;
	 add_2=1;
	 add_3=0;
	 P0=c[2];
   Delay_ms(1);	
	 P0=0x00;
	 
	 add_1=1;
	 add_2=1;
	 add_3=0;
	 P0=c[1];
   Delay_ms(1);	
	 P0=0x00;
	 
	 add_1=0;
	 add_2=0;
	 add_3=1;
	 P0=c[0];
   Delay_ms(1);	
	 P0=0x00;
	 
 }	
 
 
void main()//主函数 ---显示
{
	while(1)
	{
       datapros(DS18B20temp_data());	 
		    shuaxin();
  }
}

  • 6
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值