单片机温度传感器
一、开发板原理图
1、数码管
![]()
2、温度传感器
![]()
二、Keil程序
#include <reg52.h>
#include<stdio.h>
#define uchar unsigned char
#define uint unsigned int
sbit wei1=P2^4;
sbit wei2=P2^5;
sbit wei3=P2^6;
sbit wei4=P2^7;
sbit DQ=P2^2; //define interface
uint temp; // variable of temperature
unsigned char code table[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,
0x07,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71};
unsigned char code table1[]={0xbf,0x86,0xdb,0xcf,0xe6,0xed,0xfd,
0x87,0xff,0xef};
void delay(uint count) //delay
{
uint i;
while(count)
{
i=200;
while(i>0)
i--;
count--;
}
}
void dsreset(void) //发送重置和初始化命令
{
uint i;
DQ=0;
i=103; //将总线拉低480us~960us,单片机收到其发出的低电平应答后即可进行操作
while(i>0)i--;
DQ=1; //然后拉高总线,若DS18B20做出反应会将在15us~60us后将总线拉低
/*DQ电平从低拉到高时,产生写时序,写时序开始后DS18B20在15us~60us期间在数据线上采样, 采样到低电平写0,采样到高电平写1*/
i=4; //15us~60us等待
while(i>0)i--;
//while(DQ);
}
bit tmpreadbit(void) //读一字节
{
uint i;
bit dat;
DQ=0;i++; //i++来延时
DQ=1;i++;i++;
/*DQ电平从高拉到低,读时序被初始化,此后的15us内,单片机在数据线上采样到低电平则DS18B20读0,采样到高电平则读1。*/
dat=DQ;
i=8;while(i>0)i--;
return (dat);
}
uchar tmpread(void) //读一字节数据
{
uchar i,j,dat;
dat=0;
for(i=1;i<=8;i++)
{
j=tmpreadbit();
dat=(j<<7)|(dat>>1); //读出的数据最低位在最前面,这样刚好一个字节在DAT里
}
return(dat);
}
void tmpwritebyte(uchar dat) //写一字节到 ds18b20
{
uint i;
uchar j;
bit testb;
for(j=1;j<=8;j++)
{
testb=dat&0x01;
dat=dat>>1;
if(testb) //write 1
{
DQ=0;
i++;i++;
DQ=1;
i=8;while(i>0)i--;
}
else
{
DQ=0; //write 0
i=8;while(i>0)i--;
DQ=1;
i++;i++;
}
}
}
void tmpchange(void) //DS18B20改变
{
dsreset();
delay(1);
tmpwritebyte(0xcc); //跳过读序列号的操作(总线上仅有一个DS18B20时使用)
tmpwritebyte(0x44); //启动温度转换
//delay(100);
}
uint tmp() //获得温度
{
float tt;
uchar a,b;
dsreset();
delay(1);
tmpwritebyte(0xcc);
tmpwritebyte(0xbe);//读取暂存器中的温度数据
a=tmpread();//低八位
b=tmpread();//高八位
temp=b;
temp<<=8; //两个字节组成一个int变量
temp=temp|a;
tt=temp*0.0625; //算出来的是测到的温度,数值可到小数点后两位
temp=tt*10+0.5; //为了显示温度后的小数点后一位并作出四舍五入,因为取值运算不能取小数点后的数
return temp;
}
void display(uint temp) //显示程序
{
uchar bai,shi1,shi0,ge;
bai=temp/100;//温度数值上为十位
shi0=temp%100;//温度数值上为几点几
shi1=shi0/10;//温度上为个位,并且显示时需要加小数点
ge=shi0%10;//温度上为小数位,并已经四舍五入
wei1=1; //显示百位
wei2=0;
wei3=0;
wei4=0;
P0=table[bai];
delay(2);
wei1=0; //显示十位
wei2=1;
wei3=0;
wei4=0;
P0=table1[shi1];
delay(2);
wei1=0; //显示个位
wei2=0;
wei3=1;
wei4=0;
P0=table[ge];
delay(2);
}
// 串口初始化函数
void init_com(void)
{
TMOD=0x20; //设T0为方式1,GATE=1;
SCON=0x50;
TH1=0xFD;
TL1=0xFD;
TR1=1; //开启定时器
TI=1;
EA=1; //开启总中断
}
void main()
{
uchar a;
uint temp = 0; //温度
float ftemp = 0.0f;
init_com();
do
{
tmpchange();//让18b20开始转换温度
temp = tmp();
for(a=100;a>0;a--)
{
display(temp);
}
ftemp = temp/10.0f;
}while(1);
}
三、效果展示
![]()