用ds18b20测温度c51代码
时间: 2023-06-07 21:06:51 浏览: 43
好的,下面是用C语言编写的ds18b20温度传感器获取温度的代码:
```
#include <REG52.H>
#define DQ P1_0 // ds18b20 数据引脚
typedef unsigned char u8;
typedef unsigned int u16;
u8 TempH,TempL; // 存放温度的高位和低位
void Delay10us() // 延时函数
{
u8 i = 12;
while(i--);
}
void Ds18b20Init() // 初始化
{
DQ = 1;
Delay10us();
DQ = 0;
Delay10us();
DQ = 1;
Delay10us();
}
u8 Ds18b20ReadBit() // 读取一位数据
{
u8 dat;
DQ = 0;
Delay10us();
DQ = 1;
Delay10us();
dat = DQ;
Delay10us();
return dat;
}
void Ds18b20WriteBit(u8 bit) // 写入一位数据
{
DQ = 0;
Delay10us();
DQ = bit;
Delay10us();
DQ = 1;
Delay10us();
}
void Ds18b20WriteByte(u8 dat) // 写入一个字节
{
u8 i;
for(i = 0; i < 8; i++)
{
Ds18b20WriteBit(dat & 0x01);
dat >>= 1;
}
}
u8 Ds18b20ReadByte() // 读取一个字节
{
u8 dat,i;
for(i = 0; i < 8; i++)
{
dat >>= 1;
if(Ds18b20ReadBit())
dat |= 0x80;
}
return dat;
}
void Ds18b20GetTemp() // 获取温度
{
u8 TL,TH;
Ds18b20Init();
Ds18b20WriteByte(0xCC); // 跳过 ROM 指令
Ds18b20WriteByte(0x44); // 温度转换指令
Ds18b20Init();
Ds18b20WriteByte(0xCC); // 跳过 ROM 指令
Ds18b20WriteByte(0xBE); // 读取温度寄存器指令
TL = Ds18b20ReadByte(); // 读取温度低位
TH = Ds18b20ReadByte(); // 读取温度高位
TempH = TH;
TempL = TL;
}
void main()
{
while(1)
{
Ds18b20GetTemp();
printf("%02d.%02d°C\n",TempL,TempH); // 输出温度,并保留两位小数
}
}
```
希望能够帮到你!