📄 1.c
字号:
#include<reg51.h>
sbit DQ1=P1^0; // 数据传输线对应引脚
sbit DQ2=P1^1;
sbit io=P2^6;
int n;
unsigned char tempL=0;
unsigned char tempH=0;
void LedTest()
{
static char led=1;
led=!led;
io=led;
}
void delay(unsigned int time) //延时子程序
{
unsigned int r;
r=0;
while(r<time)
{ r++;}
return;
}
Init_DS18B20(void) //初始化子程序
{
unsigned char x=0;
DQ1=1; //置高
DQ2=1;
delay(8); //延时
DQ1=0; //发复位脉冲
DQ2=0;
delay(85);
DQ1=1; //拉高数据线
DQ2=1;
delay(14);
delay(20);
}
ReadOneChar(char *p) //读一字节数据
{
unsigned char dat1=0;
unsigned char dat2=0;
unsigned char a;
unsigned char i=0;
for(i=8;i>0;i--)
{
DQ1=1;
DQ2=1;
delay(1);
DQ1=0;
dat1>>=1;
DQ1=1;
if(DQ1)
{
dat1|=0x80;
}
p[0]=dat1;
DQ2=0;
dat2>>=1;
DQ2=1;
if(DQ2)
{
dat2|=0x80;
}
p[1]=dat2 ;
delay(4);
}
return(a);
}
WriteOneChar(unsigned char dat,n) //向DS18S20写一字节数据
{
unsigned char dat1;
unsigned char dat2;
unsigned char i=0;
dat1=dat;
dat2=dat;
for(i=8;i>0;i--)
{
if(n<1)
{
DQ1=0;
DQ1=dat1&0x01;
delay(5);
DQ1=1;
dat1>>=1;
}
else
{
DQ2=0;
DQ2=dat2&0x01;
delay(5);
DQ2=1;
dat2>>=1;
}
}
delay(4);
}
void main() //主程序
{
unsigned char n,tempH,tempL;
unsigned char p;
do
{
for(n=0;n<1;n++)
{
Init_DS18B20(); //初始化
WriteOneChar(0xcc,n); //跳过读序列号
WriteOneChar(0x44,n); //启动温度转换
delay(255);
delay(255);
delay(255);
delay(255);delay(255);
delay(255);
delay(255);
delay(255);
delay(255);
delay(255);
delay(255);
delay(255);
delay(255);
delay(255);
delay(255);
delay(255);
delay(255);
delay(255);
delay(255);
delay(255);
delay(255);
delay(255);
Init_DS18B20();
WriteOneChar(0xcc,n);
WriteOneChar(0xbe,n); //读温度寄存器
ReadOneChar(&p);
tempL=p; //读出温度低位
ReadOneChar(&p);
tempH=p; //读出温度高位
if(tempH==0xFF)LedTest();
}
}
while(1) ;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -