DS18B20温度传感器

#include 
#include 
 
typedef unsigned char uchar;
typedef unsigned int uint;
#define MAIN_Fosc		11059200UL	//ºê¶¨ÒåÖ÷ʱÖÓH
 
sbit DQ = P2^2;
sbit DU = P2^6;
sbit WE = P2^7;
 
//¶ÎÑ¡ ¹²Òõ¼«ÊýÂë¹Ü
uchar code table[]={ 
//0		1	 2     3     4     5     6     7     8
0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F,
//9     A     B	   C	 D	   E	 F		-	 .	  ¹ØÏÔʾ
0x6F, 0x77, 0x7C, 0x39, 0x5E, 0x79, 0x71, 0x40, 0x80, 0x00
                   };
//λѡ
				  //µÚ1λ	2λ	  3λ	 4λ   5λ	6λ	  7λ	8λ
uchar code T_COM[] = {0xfe, 0xfd, 0xfb, 0xf7, 0xef, 0xdf, 0xbf, 0x7f};//ÊýÂë¹ÜλÂë

void delay_ms(uint ms)
{
	 uchar i;
	 do{
	      i = MAIN_Fosc / 96000; 
		  while(--i);   //96T per loop
     }while(--ms);
}

//ÊýÂë¹ÜÏÔʾº¯Êý
void display(uchar dat)
{
	//ÏÔʾ°Ùλ
    
	
	  DU = 0;
	  P0 = table[dat/100];
	  DU = 1;
	  DU = 0;
	
  	WE = 0;
	  P0 = T_COM[0];
	  WE = 1;
	  WE = 0;
	  delay_ms(3);
 //ÏÔʾʮλ

	
	DU = 0;
	P0 = table[dat%100/10] | 0x80;
	DU = 1;
	DU = 0;
	
	WE = 0;
	P0 = T_COM[1];
	WE = 1;
	WE = 0;
	delay_ms(3);
	//ÏÔʾ¸öλ
	
	
	DU = 0;
	P0 = table[dat%10];
	DU = 1;
	DU = 0;
	
  WE = 0;
  P0 = T_COM[2];
	WE = 1;
	WE = 0; 
	delay_ms(3);
}
 

 
//º¯ÊýÃû³Æ£ºÑÓʱº¯Êý
//º¯Êý¹¦ÄÜ£ºÖ´ÐÐÒ»´ÎÐèÒª6.5us ½øÈ뺯ÊýÐèÒª11.95us
void delay_us(uchar i)
{
   	while(i--);
}
 
//º¯ÊýÃû³Æ£º³õʼ»¯º¯Êý
//º¯Êý¹¦ÄÜ£º³õʼ»¯DS18B20
bit Init_DS18B20()
{  bit ACK = 1;
   DQ = 0;                 //Ö÷»úÀ­µÍDQÏß 
	 delay_us(74);           //ÑÓʱ492.95us
	 DQ = 1;                 //Ö÷»úÀ­¸ßDQÏß
	 delay_us(5);            //µÈ´ý44.45us
   ACK = DQ;               //¶ÁÈ¡´Ó»úµÄÓ¦´ðÐźÅ
	 delay_us(74);           //ÑÓʱ492.95us
	 DQ = 1;                 //ÊÍ·ÅDQÏß ±ãÓÚÏ´ÎʹÓÃ
 	return ACK;
}

//º¯ÊýÃû³Æ£ºÐ´Êý¾Ýº¯Êý
//º¯Êý¹¦ÄÜ£ºÏòDS18B20ÖÐдÈë°ËλÊý¾Ý ´ÓµÍλ¿ªÊ¼Ð´ ²¢´æÈëDS18B20µÄ×î¸ßλ Ò»¹²Ð´°Ë´Î
void Write_byte(uchar byte)
{
    uchar i;
	  for(i = 0; i < 8;i++)
	  {
			  DQ = 0;           //дʱÐò¿ªÊ¼
			  delay_us(1);      //ÑÓʱ18.45us
			  DQ = 1;           //ÊÍ·Å×ÜÏß
			  _nop_();          //¿ÕÖ¸Áî
	      DQ = byte & 0x01; //´ÓµÍλ¿ªÊ¼Ð´Èë¡¢
        delay_us(5);     //ÑÓʱ44.45us ÔÚÕâ¶Îʱ¼äDS18B20²É¼¯ÐźÅ
			  DQ = 1;
			  _nop_();
        byte >>= 1;
     }
}
//º¯ÊýÃû³Æ£º¶ÁÊý¾Ýº¯Êý
//º¯Êý¹¦ÄÜ£º¶ÁÈ¡DS18B20µÄÊý¾Ý
uchar Read_byte()
{
	uchar i,j;
	uchar byte;
	for(i = 0;i < 8;i++)
 {
	DQ = 0;           //À­µÍDQÏß ¶ÁʱÐò¿ªÊ¼
	_nop_();          //DQÏß±£³Ö1us
	DQ = 1;           //ÊÍ·Å×ÜÏß
	_nop_();
	/*byte >>= 1;
	 if(DQ)
	   DQ |= 0x80;*/  //ºÜ¿ÉÄÜÒѾ­³¬¹ý15us
	  j = DQ;
		delay_us(10);//76.95us
		DQ = 1;
		_nop_();
		byte = (j<<7)|(byte>>1);
 } 
 return byte;
}

void main()
{
	uint M;
	uchar L,H;
	
  Init_DS18B20();
  Write_byte(0xcc);
	Write_byte(0x44);
	
  Init_DS18B20();
	Write_byte(0xcc);
	Write_byte(0xbe);
	L = Read_byte();//´æ·ÅµÍ°Ëλ
	H = Read_byte();//´æ·Å¸ßËÄλ
	M = H;
	M <<= 8;//Ïò¸ßλÒƶ¯8λ µÍ°ËλÓÃÀ´·Å L
	M |= L;//µÍ°ËλÓë¸ßËÄλÏà¼Ó
  M = M*0.0625*10 + 0.5;
  display(M);	
}

 

你可能感兴趣的:(单片机)