STC89C52 单片机 DS18B20 温度检测电路详解
STC89C52 是一款 8051 系列单片机,DS18B20 是一种数字温度传感器,它们可以通过一条单总线进行通信。因此,STC89C52 可以通过单总线与 DS18B20 进行通信,从而实现温度检测。
以下是 STC89C52 与 DS18B20 的电路连接图:
其中,DS18B20 的 VDD 接 5V 电源,GND 接地,DQ 接 STC89C52 的 P1.7 引脚。P1.7 被设置为开漏输出模式,并通过一个 4.7K 上拉电阻连接到 5V 电源。这样可以保证在总线上没有其他设备时,DQ 引脚处于高电平状态。
以下是 STC89C52 的程序代码,实现 DS18B20 的温度检测:
#include <reg52.h>
#include <intrins.h>
sbit DQ = P1^7;
void delay_us(unsigned int t)
{
while(t--)
{
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
}
}
unsigned char read_ds18b20(void)
{
unsigned char dat = 0;
unsigned char i;
for(i=0; i<8; i++)
{
DQ = 0;
_nop_();
_nop_();
dat >>= 1;
DQ = 1;
_nop_();
_nop_();
if(DQ)
{
dat |= 0x80;
}
delay_us(4);
}
return dat;
}
void write_ds18b20(unsigned char dat)
{
unsigned char i;
for(i=0; i<8; i++)
{
DQ = 0;
_nop_();
_nop_();
if(dat & 0x01)
{
DQ = 1;
}
delay_us(4);
DQ = 1;
dat >>= 1;
}
}
void init_ds18b20(void)
{
DQ = 1;
delay_us(4);
DQ = 0;
delay_us(480);
DQ = 1;
delay_us(60);
read_ds18b20();
write_ds18b20(0xCC);
write_ds18b20(0x44);
}
unsigned int get_temperature(void)
{
unsigned char temp_l, temp_h;
unsigned int temp;
init_ds18b20();
delay_us(500);
init_ds18b20();
write_ds18b20(0xCC);
write_ds18b20(0xBE);
temp_l = read_ds18b20();
temp_h = read_ds18b20();
temp = temp_h;
temp <<= 8;
temp |= temp_l;
return temp;
}
void main()
{
unsigned int temp;
while(1)
{
temp = get_temperature();
temp = temp >> 4;
printf('Temperature is %d.%d Celsius.\n', temp/16, temp%16);
delay_ms(1000);
}
}
程序中使用了几个函数,分别用于延时、读写 DS18B20 以及初始化 DS18B20。在主函数中,通过调用 get_temperature() 函数获取温度值,并将其转化为实际温度值后输出。
需要注意的是,在使用 DS18B20 时,要保证总线上只有一个 DS18B20 设备,否则会影响通信。如果需要连接多个 DS18B20,可以使用 DS2482-100 I2C 到 1-Wire 转换器来扩展总线。
原文地址: https://www.cveoy.top/t/topic/nwFw 著作权归作者所有。请勿转载和采集!