DS18B20的51驱动程序,带浮点数返回值
时间: 2023-06-18 10:02:32 浏览: 57
以下是DS18B20的51驱动程序,带浮点数返回值:
```
#include <reg52.h>
typedef unsigned char uchar;
typedef unsigned int uint;
sbit DQ = P2^3;
uchar code Table[16] = {0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f, 0x77, 0x7c, 0x39, 0x5e, 0x79, 0x71};
uchar temp;
void Delay1ms(uint);
void Delay10us(uint);
void Write_Ds18b20(uchar, uchar);
uchar Read_Ds18b20();
void Display(uchar, uchar, uchar, uchar);
float Get_Temperature();
void main()
{
while (1)
{
Display(0, 0, 0, 0);
temp = Get_Temperature();
Display(temp / 100, temp / 10 % 10, temp % 10, 0x3f);
}
}
void Delay1ms(uint i)
{
uchar j, k;
for (; i > 0; i--)
{
_nop_();
_nop_();
j = 11;
k = 190;
do
{
while (--k);
} while (--j);
}
}
void Delay10us(uint i)
{
while (i--)
{
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
}
}
void Write_Ds18b20(uchar dat, uchar id)
{
uchar i;
for (i = 0; i < 8; i++)
{
DQ = 0;
Delay10us(1);
DQ = dat & 0x01;
dat >>= 1;
Delay10us(4);
DQ = 1;
Delay10us(1);
}
}
uchar Read_Ds18b20()
{
uchar i, dat = 0;
for (i = 0; i < 8; i++)
{
DQ = 0;
Delay10us(1);
DQ = 1;
Delay10us(1);
dat |= DQ << i;
Delay10us(4);
}
return dat;
}
void Display(uchar a, uchar b, uchar c, uchar d)
{
uchar i;
uchar code DisCode[4] = {0xfe, 0xfd, 0xfb, 0xf7};
uchar DisData[4] = {a, b, c, d};
for (i = 0; i < 4; i++)
{
P0 = DisCode[i];
P1 = Table[DisData[i]];
Delay1ms(2);
P1 = 0x00;
}
}
float Get_Temperature()
{
uchar temp_low, temp_high;
float temperature;
Write_Ds18b20(0xcc, 0);
Write_Ds18b20(0x44, 0);
Delay1ms(100);
Write_Ds18b20(0xcc, 0);
Write_Ds18b20(0xbe, 0);
temp_low = Read_Ds18b20();
temp_high = Read_Ds18b20();
temperature = (float)((temp_high << 8) | temp_low) / 16.0;
return temperature;
}
```
其中,`Get_Temperature()` 函数返回浮点数类型的温度值。在主函数中,通过调用 `Get_Temperature()` 函数获取温度值,并将其显示在数码管上。