DS18B20数据上传至上位机
#include<reg52.h>
#include<intrins.h>
#include<stdio.h>
#define uint unsigned int
#define uchar unsigned char
sbit dsdq=P2^2;
void UartInit(void)
{
SCON=0x40;
TMOD &=0X0F;
TMOD |=0X20;
TH1=0xfd;
TL1=0xfd;
TR1=1;
}
void sendByte(char data_msg)
{
SBUF=data_msg;
while(!TI);
TI=0;
}
void sendString(char *str)
{
while(*str!='\0')
{
sendByte(*str);
str++;
}
}
char putchar (char c)
{
SBUF=c;
while (!TI);
TI = 0;
return c;
}
void Delay5us()
{
_nop_();
}
void Delayxus(uchar xus)
{
while(--xus);
}
void DelayMs(uint c)
{
uint a,b;
for(a=c;a>0;a--)
for(b=115;b>0;b--);
}
void Ds18B20_Reset()
{
dsdq=1;
Delayxus(1);
dsdq=0;
Delayxus(250);
dsdq=1;
Delayxus(250);
}
void Ds18B20_WriteByte(uchar dat)
{
uchar i;
bit dstemp;
for(i=0;i<8;i++)
{
dat=dat>>1;
dstemp=CY;
if(dstemp)
{
dsdq=1;
Delayxus(1);
dsdq=0;
Delayxus(1);
dsdq=1;
Delayxus(30);
}
else
{
dsdq=1;
Delayxus(1);
dsdq=0;
Delayxus(30);
}
}
}
uchar Ds18B20_ReadByte()
{
uchar i,k,dat;
for(i=0;i<8;i++)
{
dsdq=1;
Delayxus(1);
dsdq=0;
Delayxus(1);
dsdq=1;
k=dsdq;
dat=(k<<7)|(dat>>1);
Delayxus(20);
}
return dat;
}
int Ds18B20_Temper()
{
uchar tem1,tem2;
int temper;
Ds18B20_Reset();
Ds18B20_WriteByte(0xcc);
Ds18B20_WriteByte(0x44);
Ds18B20_Reset();
Ds18B20_WriteByte(0xcc);
Ds18B20_WriteByte(0xbe);
tem1=Ds18B20_ReadByte();
tem2=Ds18B20_ReadByte();
temper=tem2;
temper=(temper<<8)|tem1;
return temper;
}
void main ()
{
float tmp;
int j;
UartInit();
while(1)
{
DelayMs(1000);
tmp=Ds18B20_Temper()*0.0625;
j=(tmp*10+0.5)*10;
printf("温度为%d%d.%d%d℃\r\n",j/1000,j%1000/100,j%100/10,j%10);
}
}
上位机图片演示