《单片机实践项目》之《电子DIY》之基于51单片机温度(DS18B20)采集系统设计(串口打印数据)
程序员文章站
2024-01-06 17:31:34
程序//视频教程:B站搜索:“逗比小憨憨”#include "reg51.h"#define uchar unsigned char#define uint unsigned int#define _r 0X0A#define _d 0X0D#define T1VALUE 0XF3sbit DS18B20_DQ=P2^0; typedef struct __DS18B20{uint temperature;float temDat;uchar signFlag;...
程序
//视频教程:B站搜索:“逗比小憨憨”
#include "reg51.h"
#define uchar unsigned char
#define uint unsigned int
#define _r 0X0A
#define _d 0X0D
#define T1VALUE 0XF3
sbit DS18B20_DQ=P2^0;
typedef struct __DS18B20
{
uint temperature;
float temDat;
uchar signFlag;
uchar temp[6];
}DS18B20;
DS18B20 ds18b20={0,0.0,0,0,0,0};
uchar code display[]="Temperature:";
//函数声明
void displayTemperature(void);
void delay_ms(uint x);
void delay_us(uint x);
void Ds1820Rst(void);
uchar Ds1820Read(void);
void Ds1820Write(uchar dat);
void ReadTemperature(void);
void UartInit(void);
void Send_Char(uchar chr);
void Send_Str(uchar *str);
/////////////////////////////////////////////////////////////////////
void ReadTemperature(void)
{
uchar TH,TL;
ds18b20.temperature=0;
ds18b20.temp[0]=0;
ds18b20.temp[1]=0;
ds18b20.temp[2]=0;
ds18b20.temp[3]=0;
Ds1820Rst();
Ds1820Write(0xcc);
Ds1820Write(0x44);
Ds1820Rst();
Ds1820Write(0xcc);
Ds1820Write(0xbe);
TL=Ds1820Read();
TH=Ds1820Read();
ds18b20.temperature=TH;
ds18b20.temperature<<=8;
ds18b20.temperature=ds18b20.temperature|TL;
if(ds18b20.temperature<0x0fff)
ds18b20.signFlag=0;
else
{
ds18b20.temperature=~ds18b20.temperature+1;
ds18b20.signFlag=1;
}
ds18b20.temperature=ds18b20.temperature*(0.625);
P0=ds18b20.temperature;
}
void UartInit(void)
{
TMOD = 0x20;
PCON = 0x00;
SCON = 0x50;//0101 0000
TH1=T1VALUE;
TL1=T1VALUE;
TR1=1;
}
void Send_Char(uchar chr)
{
SBUF=chr;
while(!TI);
SCON&=~(1<<1);
}
void Send_Str(uchar *str)
{
while(*str!='\0')
{
SBUF=*str;
while(!TI);
TI=0;
str++;
}
SCON&=~(1<<1);
}
uchar Ds1820Read(void)
{
uchar j=0,dat=0;
for(j=0;j<8;j++)
{
DS18B20_DQ=0;
dat>>=1;
DS18B20_DQ=1;
if(DS18B20_DQ)
dat|=0x80;
delay_us(10);
}
return dat;
}
void Ds1820Write(uchar dat)
{
uchar j=0;
for (j=0;j<8;j++)
{
DS18B20_DQ=0;
DS18B20_DQ=dat&0x01;
delay_us(10);
DS18B20_DQ=1;
dat>>=1;
}
}
void displayTemperature(void)
{
ReadTemperature();
ds18b20.temp[0]=ds18b20.temperature/1000+'0';
ds18b20.temp[1]=ds18b20.temperature%1000/100+'0';
ds18b20.temp[2]=ds18b20.temperature%100/10+'0';
ds18b20.temp[3]=ds18b20.temperature%10+'0';
Send_Str(display);
if(ds18b20.temp[0]!='0')
{
Send_Char(ds18b20.temp[0]);
}
Send_Char(ds18b20.temp[1]);
Send_Char(ds18b20.temp[2]);
Send_Char('.');
Send_Char(ds18b20.temp[3]);
SBUF=_r;
SBUF=_d;
while(!TI);
SCON&=~(1<<1);
}
int main()
{
UartInit();
while(1)
{
displayTemperature();
delay_ms(1000); //750
}
return 0;
}
void delay_ms(uint x)
{
uint i,j;
for(i=0;i<x;i++)
for(j=0;j<110;j++);
}
void delay_us(uint x)
{
while(x--);
}
void Ds1820Rst(void)
{
DS18B20_DQ = 1;
delay_us(4);
DS18B20_DQ = 0;
delay_us(100);
DS18B20_DQ = 1;
delay_us(40);
}
本文地址:https://blog.csdn.net/liuxianfei0810/article/details/107297967