📄 4 ds18b20.c
字号:
// DS18B20温度传感器//
#include <reg51.h>
sbit DQ =P3^3; //定义通信端口
void delay1(unsigned int i)
{
while(i--);
}
reset(void)
{
unsigned char x=0;
DQ = 1; //DQ复位
delay1(8); //稍做延时
DQ = 0; //单片机将DQ拉低
delay1(80); //精确延时 大于 480us
DQ = 1; //拉高总线
delay1(14);
x=DQ; //稍做延时后 如果x=0则初始化成功 x=1则初始化失败
delay1(20);
}
//读一个字节
unsigned char read_byte(void)
{
unsigned char i=0;
unsigned char dat = 0;
for (i=8;i>0;i--)
{
DQ = 0; // 给脉冲信号
dat>>=1;
DQ = 1; // 给脉冲信号
if(DQ)
dat|=0x80; /*LSB to MSB*/
delay1(4);
}
return(dat);
}
//写一个字节
write_byte(unsigned char dat)
{
unsigned char i=0;
for (i=8; i>0; i--)
{
DQ = 0;
DQ = dat&0x01;
delay1(5);
DQ = 1;
dat>>=1;
}
}
//读取温度
unsigned char read_temperature(void)
{
unsigned char a=0;
unsigned char b=0;
reset();
write_byte(0xCC); // 跳过读序号列号的操作
write_byte(0x44); // 启动温度转换
delay1(10000);
reset();
write_byte(0xCC); //跳过读序号列号的操作
write_byte(0xBE); //读取温度寄存器等(共可读9个寄存器) 前两个就是温度
a=read_byte();
b=read_byte();
b=b<<4;
a=a>>4;
return(a|b);
}
char t;
initial();
while(1)
{
t=read_temperature();
set_addr(0);
send_d(t/10+48);
send_d(t%10+48);
delay1(10000);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -