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

📄 ds18b20.c

📁 基于51单片机和ds18b20的测温系统完整设计
💻 C
字号:
//for ds18b20 with 89c51 at P1_0,2*4 7Seg LED at P0&P2
//clock 11.0592MHz
//Authur:Gu Wenfu
#include<regx51.h>
#include<absacc.h>

unsigned char left,middle,right;
unsigned char final;

unsigned char code LEDMAP[]=
{
	0x3f, 0x06, 0x5b, 0x4f, 0x66, 
	0x6d, 0x7d, 0x07, 0x7f, 0x6f,
	0x00, 0x40, 0x79
};//0x40 is "-",0x79 is "E"

void reset()
{
	unsigned int i;
	P1_0=0;
	i=60;
	while(i>0)	i--;          //delay for at least 480uS(11.0592MHz) for reset impulse(482us)
	P1_0=1;
	i=4;
	while(i>0)	i--;     	  //delay a period for ds18b20 to detect the rising edge(34us)
	i=60;
	while(i>0)	i--;          //delay for at least 480uS(11.0592MHz) for presence impulse(482us)
}

readbit()
{
	unsigned int i;
 	bit value;
 	P1_0=0;
	i++; //(3us)
 	P1_0=1;
	i++;
	i++; //short delay(6us)
 	value=P1_0; 
 	i=6;
	while(i>0)	i--;  //delay(50us)
 	return((char)value);
}

readbyte()
{
	unsigned char i,value,result;
	value=0;
 	result=0;
	for(i=1;i<=8;i++)
 	{
		value=readbit();
 		result=(value<<7)|(result>>1); //build the entire byte from the lower bit
 	}
	return(result);
}

void writebyte(unsigned char date)
{
	unsigned int i;
	unsigned char j;
	bit inbit;
	for(j=1;j<=8;j++)
	{
		inbit=date&0x01;
  		date=date>>1;
  		if(inbit) 	//case of write 1
  		{
   			P1_0=0;
   			i++;
			i++;		//(6us)
			P1_0=1;
			i=8;
			while(i>0)	i--;	 //(68us)
		}
  		else       	 //case of write 0
  		{
   			P1_0=0;
   			i=8;
			while(i>0)	i--;     //(68us)
   			P1_0=1;
   			i++;
			i++;   		//(6us)
		}
	}
}

trans_temperature()
{
	reset();
	writebyte(0xcc);  //skip rom
	writebyte(0x44);  //transform the temperature into data   //启动温度转换
}

get_temperature()
{
	unsigned char temperl,temperh,result;
   	reset();
	XBYTE[0x000]=LEDMAP[10];
	XBYTE[0x200]=LEDMAP[middle];
	writebyte(0xcc);  //skip rom
	writebyte(0xbe);  //read the data
	temperl=readbyte();
	temperh=readbyte();
	result=(temperl>>4)|(temperh<<4);//drop the lowerst 4 bits and the highest 4 bits to build one byte with unit "1" instead of "0.0625"
	return(result);
}

main()
{
	left = 0;
	middle = 0;
	right = 0;
	while(1)
	{
 		 trans_temperature();
		 XBYTE[0x000]=LEDMAP[10];
		 XBYTE[0x400]=LEDMAP[left];
		 final=get_temperature();
		 if(final>0x80)
		 {
		 	left=11;
			final=~final+1;
			middle=final/10;
			right=final%10;
		 }
		 else
		 {
			left=final/100;
			final=final%100;
			middle=final/10;
			right=final%10;
		 }
		 XBYTE[0x000]=LEDMAP[10];
		 XBYTE[0x100]=LEDMAP[right];
	}
}

⌨️ 快捷键说明

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