51单片机温度传感器代码
时间: 2023-04-05 15:01:17 浏览: 60
以下是51单片机温度传感器代码的示例:
#include <reg52.h>
#include <intrins.h>
typedef unsigned char uchar;
typedef unsigned int uint;
sbit DQ = P3^7; //定义DS18B20的数据引脚
uchar code table[] = "Temperature:"; //定义显示字符串
uchar code table1[] = "C"; //定义显示字符串
uchar temp; //定义温度变量
void delay(uint i) //延时函数
{
while(i--);
}
void Init_DS18B20(void) //初始化DS18B20
{
uchar i;
DQ = 1;
delay(10);
DQ = 0;
delay(1000);
DQ = 1;
delay(10);
i = DQ;
delay(500);
}
void Write_DS18B20(uchar dat) //向DS18B20写入一个字节的数据
{
uchar i, j;
for(j=0; j<8; j++)
{
DQ = 0;
_nop_();
DQ = dat & 0x01;
_nop_();
DQ = 1;
dat >>= 1;
}
}
uchar Read_DS18B20(void) //从DS18B20读取一个字节的数据
{
uchar i, j, dat = 0;
for(j=0; j<8; j++)
{
DQ = 0;
_nop_();
DQ = 1;
_nop_();
_nop_();
dat |= DQ << j;
}
return dat;
}
void Convert_DS18B20(void) //启动DS18B20温度转换
{
Init_DS18B20();
Write_DS18B20(0xcc);
Write_DS18B20(0x44);
}
uchar Read_Temper_DS18B20(void) //从DS18B20读取温度值
{
uchar a, b;
Init_DS18B20();
Write_DS18B20(0xcc);
Write_DS18B20(0xbe);
a = Read_DS18B20();
b = Read_DS18B20();
temp = (b<<4)|(a>>4);
return temp;
}
void Display_Temper(void) //显示温度值
{
uchar i;
for(i=0; i<12; i++)
{
P0 = table[i];
delay(1000);
}
P0 = temp/10 + '0';
delay(1000);
P0 = temp%10 + '0';
delay(1000);
for(i=0; i<1; i++)
{
P0 = table1[i];
delay(1000);
}
}
void main(void)
{
while(1)
{
Convert_DS18B20();
Read_Temper_DS18B20();
Display_Temper();
}
}
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)