|

- #include <reg51.h>
- #include <intrins.h>
- #define uint unsigned int
- #define uchar unsigned char
- sbit DQ = P3^6;
- uchar code DSY_CODE[] =
- { 0X3F,0X06,0X5B,0X4F,0X66,0X6D,0X7D,0X07,0X7F,0X6F,0X00};
- uchar code df_Table[] = {0,1,1,2,3,3,4,4,5,6,6,7,8,8,9,9};
- uchar CurrentT = 0;
- uchar Temp_Value[]={0x11,0x22};
- uchar Display_Digit[]={0,0,0,0};
- bit DS18B20_IS_OK = 1;
- void Delay(uint x)
- {
- while(--x);
- }
- uchar Init_DS18B20()
- {
- uchar status;
- DQ = 1;
- Delay(8);
- DQ = 0;
- Delay(90);
- DQ = 1;
- Delay(8);
- DQ = 1;
- return status;
- }
- uchar ReadOneByte()
- {
- uchar i,dat=0;
- DQ = 1;
- _nop_();
- for(i=0;i<8;i++)
- {
- DQ = 0;
- dat >>= 1;
- DQ = 1;
- _nop_();
- _nop_();
- if(DQ)
- dat |= 0X80;
- Delay(30);
- DQ = 1;
- }
- return dat;
- }
- void WriteOneByte(uchar dat)
- {
- uchar i;
- for(i=0;i<8;i++)
- {
- DQ = 0;
- DQ = dat& 0x01;
- Delay(5);
- DQ = 1;
- dat >>= 1;
- }
- }
- void Read_Temperature()
- {
- if(Init_DS18B20() ==1 )
- DS18B20_IS_OK = 0;
- else
- {
- WriteOneByte(0xcc);
- WriteOneByte(0x44);
- Init_DS18B20();
- WriteOneByte(0xcc);
- WriteOneByte(0xbe);
- Temp_Value[0] = ReadOneByte();
- Temp_Value[1] = ReadOneByte();
- DS18B20_IS_OK=1;
- }
- }
- void Display_Temperature()
- {
- uchar i;
- uchar t=150;
- uchar ng=0, np=0;
- if ( (Temp_Value[1] & 0xf8) == 0xf8)
- {
- Temp_Value[1] = ~Temp_Value[1];
- Temp_Value[0] = ~Temp_Value[0]+1;
- if (Temp_Value[0] == 0x00) Temp_Value[1]++;
- ng=1;np=0xfd;
- }
- Display_Digit[0] = df_Table[ Temp_Value[0] & 0x0f ];
- CurrentT = ((Temp_Value[0] & 0xf0)>>4) | ((Temp_Value[1] & 0x07)<<4);
- Display_Digit[3] = CurrentT / 100;
- Display_Digit[2] = CurrentT % 100 / 10;
- Display_Digit[1] = CurrentT % 10;
- if (Display_Digit[3] == 0)
- {
- Display_Digit[3] = 10;
- np = 0xfb;
- if (Display_Digit[2] == 0)
- {
- Display_Digit[2] = 10;
- np = 0xf7;
- }
- }
- for (i=0;i<30;i++)
- {
- P0=0x39;P2=0x7f;Delay(t);P2=0xFF;
- P0=0x63;P2=0xbf;Delay(t);P2=0xff;
- P0=DSY_CODE[Display_Digit[0]];
- P2=0xDF;Delay(t);P2=0xff;
- P0=(DSY_CODE[Display_Digit[1]]) | 0x80;
- P2=0xef;Delay(t);P2=0xff;
- P0=DSY_CODE[Display_Digit[2]];
- P2=0xf7;Delay(t);P2=0xff;
- P0=DSY_CODE[Display_Digit[3]];
- P2=0xfb; Delay(t); P2=0xff;
- if (ng)
- {
- P0 = 0x40; P2 = np; Delay(t); P2=0xff;
- }
- }
- }
- void main()
- {
- Read_Temperature();
- Delay(50000);
- Delay(50000);
- while(1)
- {
- Read_Temperature();
- if(DS18B20_IS_OK)
- Display_Temperature();
- }
- }
復(fù)制代碼
|
|