#include <reg52.H> #include <intrins.h>
sbit D18B20=P3^7; bit flag;
unsigned char Temperatured; unsigned char temp_data[2]; unsigned char temp_dis[6]={0xFF,0xFF,0xFF,0xFF,0xFF}; unsigned char temp_tab[16]={0x00,0x01,0x01,0x02,0x03,0x03,0x04,0x04,0x05,0x06,0x07,0x08,0x09,0x09};
void Disp_temperatuer();void read_bytes (void); void TempDelay (unsigned int us); void Init18b20 (void);void WriteByte (unsigned char idata wr); unsigned char ReadByte (void);
void Disp_temperatuer() { temp_dis[4]= temp_data[0]&0x0f; temp_dis[0]= temp_tab[temp_dis[4]]+0x30; temp_dis[3]= (((temp_data[0]&0xf0)>>4)|((temp_data[1]&0x0f)<<4)); temp_dis[5]= (temp_dis[3]%100); temp_dis[2]= (temp_dis[3]%100)/10+0x30; temp_dis[1]= temp_dis[3]%10+0x30; }
void read_bytes (void) { Init18b20(); WriteByte(0xcc); WriteByte(0x44);
TempDelay(5000);
Init18b20(); WriteByte(0xcc); WriteByte(0xbe); temp_data[0] = ReadByte(); TempDelay(2); temp_data[1] = ReadByte(); TempDelay(2); }
unsigned char ReadByte (void) //读取单字节
{ unsigned char idata Ti,u=0; for(Ti=0;Ti<8;Ti++) { D18B20 = 0; u >>= 1; D18B20 = 1; TempDelay(3); if(D18B20==1) u |= 0x80; TempDelay (1); _nop_(); D18B20 = 1; } return(u); }
void WriteByte (unsigned char idata wr) //单字节写入
{ unsigned char idata i; for (i=0;i<8;i++) { D18B20 = 0; _nop_(); D18B20=wr&0x01; TempDelay(3); //delay 45 uS //5
_nop_(); _nop_(); D18B20=1; wr >>= 1; _nop_(); } }
void Init18b20 (void) { D18B20=1; _nop_(); D18B20=0; TempDelay(100); //delay 530 uS//80
_nop_(); D18B20=1; TempDelay(13); //delay 100 uS//14
_nop_(); _nop_(); _nop_(); if(D18B20==0) flag = 1; //detect 1820 success!
else flag = 0; //detect 1820 fail!
TempDelay(10); //20
_nop_(); _nop_(); D18B20 = 1; }
void TempDelay (unsigned int us) { while(us--); }
|