标题:
18b20与单片机串口结合,实时接收,检测温度程序
[打印本页]
作者:
mpc112
时间:
2019-4-25 18:09
标题:
18b20与单片机串口结合,实时接收,检测温度程序
18b20检测温度,显示在数码管上,同过串口发送到电脑
单片机源程序如下:
#include <at89x51.h>
sbit DQ = P2 ^ 6; //定义端口DQ
sbit led1 =P2^0;
sbit led2 =P2^1;
sbit led3 =P2^2;
sbit led4 =P2^3;
#define BCD unsigned char
#define shi unsigned char
unsigned char tx[10]={0,0,0x2E,0,0,0,0,0xDF,0x43,0x0A};
unsigned code table[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,
0xf8,0x80,0x90};
void Delay(int num)//延时函数
{
while(num--) ;
}
void Delaynms(unsigned int di) //延时
{
unsigned int da,db;
for(da=0;da<di;da++)
for(db=0;db<100;db++);
}
void Init_DS18B20(void)//初始化ds1820
{
unsigned char 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);
}
unsigned char ReadOneChar(void)//读一个字节
{
unsigned char i=0;
unsigned char dat = 0;
for (i=8;i>0;i--)
{
DQ = 0; // 给脉冲信号
dat>>=1;
DQ = 1; // 给脉冲信号
if(DQ)
dat|=0x80;
Delay(4);
}
return(dat);
}
void WriteOneChar(unsigned char dat)//写一个字节
{
unsigned char i=0;
for (i=8; i>0; i--)
{
DQ = 0;
DQ = dat&0x01;
Delay(2);
DQ = 1;
dat>>=1;
}
}
void ReadTemperature(void)//读取温度
{
unsigned char a=0;
unsigned char b=0;
unsigned char Data_L=0;
unsigned char num=0;
Init_DS18B20();
WriteOneChar(0xCC); // 跳过读序号列号的操作
WriteOneChar(0x44); // 启动温度转换
Init_DS18B20();
WriteOneChar(0xCC); //跳过读序号列号的操作
WriteOneChar(0xBE); //读取温度寄存器
a=ReadOneChar(); //读低8位
b=ReadOneChar(); //读高8位
tx[0] = (a/16+b*16)/10; //整数部分
tx[1] = (a/16+b*16)%10;
Data_L=a&0X0F;
for(num=3;num<7;num++) //小数部分
{
Data_L=Data_L*10; //10 //100 //40 //80
tx[num]=Data_L/16; //0 //6 //2 //5
Data_L=Data_L%16; //10 //4 //8
}
}
void Display_SMG(void)
{
unsigned char a;
for(a=0;a<=50;a++)
{
P0=table[tx[0]];
P2_0 = 0;
Delaynms(5);
P2_0 = 1;
P0=(table[tx[1]])&0x7f;
P2_1 = 0;
Delaynms(5);
P2_1 = 1;
P0=table[tx[3]];
P2_2 = 0;
Delaynms(5);
P2_2 = 1;
P0=table[tx[4]];
P2_3 = 0;
Delaynms(5);
P2_3 = 1;
}
}
void b(unsigned int baud)
{
SCON=0x50;//0101 0000
TMOD &=0x0F;
TMOD |=0x20;
TH1=TL1=(256-11059200)/12/2/16/baud;
ET1=0;
TR1=1;
}
void main(void)
{
BCD w,a,s,d;
shi z,x,c,v;
Init_DS18B20();
while(1)
{
ReadTemperature();
Display_SMG();
b(9600);
w=(table[tx[0]]/10*16)+(table[tx[0]]%10);
z=((w>>4)*10+(w&0x0f));
SBUF=z;
while(TI==0);
TI=0;
Delay(1000);
a=(table[tx[1]]&0x7f/10*16)+(table[tx[1]]&0x7f%10);
x=((a>>4)*10+(a&0x0f));
SBUF=x;
while(TI==0);
TI=0;
Delay(1000);
s=(table[tx[3]]/10*16)+(table[tx[3]]%10);
c=((s>>4)*10+(s&0x0f));
SBUF=c;
while(TI==0);
TI=0;
Delay(1000);
d=(table[tx[4]]/10*16)+(table[tx[4]]%10);
v=((d>>4)*10+(d&0x0f));
SBUF=v;
while(TI==0);
TI=0;
Delay(1000);
}
}
复制代码
所有资料51hei提供下载:
串口温度.rar
(40.68 KB, 下载次数: 17)
2019-4-25 18:06 上传
点击文件名下载附件
温度18b20
下载积分: 黑币 -5
欢迎光临 (http://www.51hei.com/bbs/)
Powered by Discuz! X3.1