📄 ds18b20.h
字号:
#define uchar unsigned char
#define uint unsigned int
sbit DQ =P2^6; //定义通信端口
uchar disp[6]; //待显示的数据,高3位整数部分,低1位小数部分
//延时函数
void delay(unsigned int i)
{
while(i--);
}
//初始化函数
Init_DS18B20(void)
{
uchar x=0;
DQ = 1; //DQ复位
delay(8); //稍做延时
DQ = 0; //单片机将DQ拉低
delay(80); //精确延时 大于 480us
DQ = 1; //拉高总线
delay(14);
x=DQ; //稍做延时后 如果x=0则初始化成功 x=1则初始化失败
delay(20);
}
//读一个字节
ReadOneChar(void)
{
uchar i=0;
uchar dat = 0;
for (i=8;i>0;i--)
{
DQ = 0; // 给脉冲信号
dat>>=1;
DQ = 1; // 给脉冲信号
if(DQ)
dat|=0x80;
delay(4);
}
return(dat);
}
//写一个字节
WriteOneChar(unsigned char dat)
{
unsigned char i=0;
for (i=8; i>0; i--)
{
DQ = 0;
DQ = dat&0x01;
delay(5);
DQ = 1;
dat>>=1;
}
delay(4);
}
//读取温度
void ReadTemperature(void)
{
uchar a=0,temp;
uchar b=0;
Init_DS18B20();
WriteOneChar(0xCC); // 跳过读序号列号的操作
WriteOneChar(0x44); // 启动温度转换
Init_DS18B20();
WriteOneChar(0xCC); //跳过读序号列号的操作
WriteOneChar(0xBE); //读取温度寄存器等(共可读9个寄存器) 前两个就是温度
a=ReadOneChar(); //读取温度值低位
b=ReadOneChar(); //读取温度值高位
temp=b;
temp&=0xf0;
if(temp==0) //正温
{
disp[0]=((b<<4)|(a>>4))/100+'0';
disp[1]=(((b<<4)|(a>>4))%100)/10+'0';
disp[2]=(((b<<4)|(a>>4))%100)%10+'0';
disp[3]='.';
disp[4]=((a&0x0f)*625)/1000+'0';
}
else //负温
{
if(a==0)
{
a=~a+1;
b=~b+1;
}
else
{
a=~a+1;
b=~b;
}
disp[0]='-';
disp[1]=((b<<4)|(a>>4))/10+'0';
disp[2]=((b<<4)|(a>>4))%10+'0';
disp[3]='.';
disp[4]=((a&0x0f)*625)/1000+'0';
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -