⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 18b20led.c

📁 DS18B20实时测量温度
💻 C
字号:
#include <reg52.H>
//----------------------------------------------------------------------------------------------------------------
#define uint unsigned int
#define uchar unsigned char
//----------------------------------------------------------------------------------------------------------------
sbit DQ   = P0^0;           // 定义DS18B20数据线
sbit BEEP = P0^2;             //蜂鸣器
sbit SWH  = P0^1;
uchar code dis_7[10]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};
void delay(uint t)
 {
  while(t--)
   ;
 }
void Init_DS18B20(void)//初始化ds1820
{
	uchar x=0;
	DQ = 1;    //DQ复位
	delay(8);  //稍做延时
	DQ = 0;    //单片机将DQ拉低
	delay(80); //精确延时 大于 480us
	DQ = 1;    //拉高总线
	delay(14);
	x=DQ;      //稍做延时后 如果x=0则初始化成功 x=1则初始化失败
	delay(20);
}
/******************************************************************************/
uchar ReadOneChar(void)//读一个字节
{
	uchar i=0;
	uchar dat = 0;
	for (i=8;i>0;i--)
	{
		DQ = 0; // 给脉冲信号
		dat>>=1;
		DQ = 1; // 给脉冲信号
		if(DQ)
		dat|=0x80;
		delay(4);
	}
	return(dat);
}

/******************************************************************************/
void WriteOneChar(uchar dat)//写一个字节
{
	uchar i=0;
	for (i=8; i>0; i--)
	{
		DQ = 0;
		DQ = dat&0x01;
	    delay(5);
		DQ = 1;
		dat>>=1;
	}
}
/******************************************************************************/
uint ReadTemperature(void)//读取温度
{
	uchar a=0;
	uchar b=0;
	uint t=0;
	float tt=0;
	Init_DS18B20();     //第一次复位,执行温度转换
    WriteOneChar(0xCC); // 跳过读序号列号的操作
    WriteOneChar(0x44); // 启动温度转换
    Init_DS18B20();     // 第二次复位,读数据
    WriteOneChar(0xCC); //跳过读序号列号的操作
    WriteOneChar(0xBE); //读取温度寄存器
    a=ReadOneChar();    //读低8位
    b=ReadOneChar();    //读高8位
    t=b;
    t<<=8;
    t=t|a;
    tt=t*0.0625;
    t= tt*10+0.5;       //放大10倍输出并四舍五入
    return(t);
}
main()
{
  uint t;
  while(1)
  { 
    t= ReadTemperature();
	if(t>999)
	{
	  P1=dis_7[t/1000];
	  P3=0xfe;
	  delay(200);
	  P1=dis_7[(t%1000)/100];
	  P3=0xfd;
	  delay(200);
	
	}
	else
	{
	   P1=dis_7[t/100];
	   P3=0xfd;
	   delay(200);
	   
	}
	P1=(dis_7[(t%100)/10]&0x7f);
	P3=0xfb;
	delay(200);	
	P1=dis_7[t%10];
	P3=0xf7;
	if(t<1000)
	 {
	   SWH=0;
	   BEEP=1;
	 }	
/*	else if(t==999)	  	 
	   SWH=1;	 
	else if(t==1000)
     BEEP=0; */
	else
	 {
	 SWH=1; 
	 BEEP=0;
	 }
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -