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

📄 18b20.c

📁 51单片机读取18B20数字温度传感器的程序包。通讯总线DQ为P1^5
💻 C
字号:
#include<reg51.h>
#include<intrins.h>
#define uchar unsigned char
#define uint unsigned int
sbit DQ=P1^5;
uchar code tab[]={0x88,0xeb,0x4c,0x49,0x2b,0x19,0x18,0xcb,0x08,0x09};//0123456789

void delay(uchar i)
{
     while(--i);
    
}
//初始化函数
bit Init_DS18B20()
{
 	bit x;
 	DQ = 1;    //DQ复位
	_nop_();
	_nop_();
	DQ = 0;    //单片机将DQ拉低
	delay(250); //精确延时 大于 480us
	DQ = 1;    //拉高总线
 	delay(80);
 	x=!DQ;      //稍做延时后 如果x=0则初始化成功 x=1则初始化失败
 	delay(170);
 	DQ=1;
 	return(x);
}
//读一个字节
ReadOneChar(void)
{
	uchar i;
	uchar rw =0x00;
	for (i=8;i>0;i--)
 	{
 		DQ = 1;    
 		_nop_();
 		_nop_();
		DQ = 0; // 给脉冲信号
		rw>>=1;
 		DQ = 1; // 给脉冲信号
	 	if(DQ)
		rw|=0x80;
	 	delay(8);
	}
 	return(rw);
}
//写一个字节
WriteOneChar(uchar ww)
{
 	uchar i;
 	for (i=8; i>0; i--)
 	{
 	 	DQ = 1;    
  		_nop_();
  		_nop_();
 		DQ = 0;
 		DQ = ww&0x01;
 	 	delay(20);
		ww>>=1;
  		_nop_();
 	}
	
}
//读取温度
ReadTemperature(void)
{
	unsigned char a=0;
	unsigned char b=0;
	unsigned char t=0;
	while(Init_DS18B20());
	WriteOneChar(0xCC); // 跳过读序号列号的操作
	WriteOneChar(0x44); // 启动温度转换
	while(Init_DS18B20());
	WriteOneChar(0xCC); //跳过读序号列号的操作
	WriteOneChar(0xBE); //读取温度寄存器等(共可读9个寄存器) 前两个就是温度
	a=ReadOneChar();   //读取温度值低位
	b=ReadOneChar();   //读取温度值高位
	a=a>>4;            //低位右移4位,舍弃小数部分
	b=b<<4;            //高位左移4位,舍弃符号位
	t=b|a;             
	return(t);
}
void display(uchar i)
{
	uchar j,word1,word2;
	word1=i%10;
	word2=i/10;
 	SBUF=tab[word1];
	while(!TI);
	TI=0;
	SBUF=tab[word2];
	while(!TI);
	TI=0;
	for(j=0;j<4;j++)
	{
	 	SBUF=0xff;
		while(!TI);
		TI=0;
	}
}
void main()
{
	uchar upt;
	SCON=0X00;

	while(1)
	{
	 	upt=ReadTemperature();
		display(upt);
		
	}
}

⌨️ 快捷键说明

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