📄 ds18b20.c
字号:
#include <reg52.h>
#include<intrins.h>
#define uchar unsigned char
#define uint unsigned int
void lcd_wrcmd(uchar lcdcmd);
void lcd_moveto(uchar position);
void lcd_wrdata(uchar lcddata);
void lcd_string(uchar position,uchar count,uchar *strpoint);
void lcd_init() ;
void lcd_cls() ;
sbit DQ =P4^2;
sbit LED1 =P4^3;
uchar Temp_data[4];
void Delay1us(uchar us) //延时1us
{
while(us)
{
_nop_();
--us;
}
}
//延时1ms
void Delay1ms(uchar ms)
{
Delay1us(1000);
}
//ds18b20复位,返回0,设备正常,返回1,没有设备或设备不正常
bit resetpulse(void)
{
unsigned char i;
bit RstFlag;
RstFlag=1;
DQ=0;
for(i=0;i<40;i++)//480us延时
{
Delay1us(15);
}
DQ=1;
for(i=0;i<4;i++)//15~60us延时
{
Delay1us(15);
}
for(i=0;i<16;i++)//60~240us延时
{
Delay1us(15);
if(DQ==0)
RstFlag=0;
}
for(i=0;i<16;i++)
{
Delay1us(15);
}
return(RstFlag);
}
//ds18b20写命令
void writecommandtods18b20(uchar command)
{
uchar i;
DQ=1;
Delay1us(1);
for(i=0;i<8;i++)
{
DQ=0;
Delay1us(15);
DQ=command&0x1;//低位在先
Delay1us(15);
Delay1us(15);
Delay1us(15);
DQ=1;
command=command>>1;
Delay1us(1);
}
}
//ds18b20读命令
unsigned char readdatafromds18b20(void)
{
uchar i;
uchar temp;
temp=0;
DQ=1;
Delay1us(1);
for(i=0;i<8;i++)
{
DQ=0;
Delay1us(15);
DQ=1;
Delay1us(2);
temp=temp>>1;
if(DQ==1)
{
temp=temp+0x80;//先读到最高位,再依次右移
}
Delay1us(15);
Delay1us(15);
Delay1us(15);
}
return(temp);
}
//跳过读序号列号的操作
void SkipRomCode(void)
{
resetpulse(); //复位
writecommandtods18b20(0xCC);// 跳过读序号列号的操作
}
//启动转换
void StartADC(void)
{
resetpulse(); //复位
writecommandtods18b20(0xCC);//广播
writecommandtods18b20(0x44);//启动温度转换,12位,需时700ms
}
unsigned int GetTempValue(void)
{
unsigned i,j;
unsigned int T;
SkipRomCode();
writecommandtods18b20(0xBE);//读取温度值的命令
i=readdatafromds18b20(); //温度低八位
j=readdatafromds18b20(); //温度高八位
StartADC();
T=i+j*256;
if(T==0xFFFF) return 0xFFFF;
if(T>0x8000) //温度为负
{
T=~T+1;
return(0x8000+T*5/8);
}
else //温度位正
{
return(T*5/8);
}
}
void main(void)
{
uint w;
P4SW=0x70;
Delay1ms(10);
lcd_init();
Delay1ms(10);
SkipRomCode(); //主机发布跳过读序号列号的操作
writecommandtods18b20(0x44);//启动温度转换
lcd_string(4, 8,"NOW TEMP");
lcd_string(25,6," C");
while(1)
{
Delay1ms(700); //延时700ms
w=GetTempValue();
Temp_data[0] = (w%1000)/100+0x30;// 十位
Temp_data[1] = (w%100)/10+0x30;//个位
Temp_data[2] = 0x2e;
Temp_data[3] = w%10+0x30;//小数位
Temp_data[4] = 0xdf;
lcd_string(25,5,&Temp_data[0]);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -