|
/***************读取DS18B20温度,通共阴数码管显示**************/
#include<reg51.h>
#define uchar unsigned char
#define uint unsigned int
code uchar seven_seg[] = {0xFC,0x60,0xDA,0xF2,0x66,0xB6,0xBE,0xE0,0xFE,0xF6,0x77,0x7C,0x39,0x5E,0x79,0x71};
uint timer;
uint temp;
sbit DQ = P1^0;
sbit LED = P0^1;
sbit KEY = P0^2;
sbit BIT1 = P0^7;
sbit BIT2 = P0^6;
sbit BIT3 = P0^5;
sbit BIT4 = P0^4;
void delay(uint x)
{
while(x--);
}
void Init_DS18B20(void)
{
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);
}
/******************************从18B20中读一个字节****************************/
uchar Read_OneChar(void)
{
uchar i = 0;
uchar dat = 0;
for (i=8;i>0;i--)
{
DQ = 0; // 给脉冲信号
dat >>= 1;
DQ = 1; // 给脉冲信号
if(DQ)
dat |= 0x80;
delay(8);
}
return(dat);
}
/******************************向18B20中写一个字节****************************/
void Write_OneChar(uchar dat)
{
uchar i=0;
for (i=8; i>0; i--)
{
DQ = 0;
DQ = dat&0x01;
delay(10);
DQ = 1;
dat >>= 1;
}
delay(8);
}
/***********************************读取温度**********************************/
uint Read_Temperature(void)
{
float zs,xs; //zs=整数,xs=小数
uchar temp_L,temp_H; //温度低8位,和高8位
uint t; //返回值
EA=0; //关中断,以免意外
Init_DS18B20();
Write_OneChar(0xcc); // 跳过读序号列号的操作
Write_OneChar(0xbe); // 读取温度寄存器等(共可读9个寄存器) 前两个就是温度
temp_L = Read_OneChar(); //读取温度值低位
temp_H = Read_OneChar(); //读取温度值高位
Init_DS18B20();
Write_OneChar(0xcc); //跳过读序号列号的操作
Write_OneChar(0x44); //启动温度转换
xs = 0x0f & temp_L; //低四位的后四位得到小数部分
xs = xs/10;
zs = ((temp_L&0xf0)>> 4)|((temp_H&0x0f)<< 4);//低位右移4位,高位左移4位,得到整数部分
t=(zs+xs)*10; //整数+小数等于数据,但又小数点,所以数据X10倍,变成整数
EA=1; //开中断
return(t);
}
/********延时函数************/
void delay_time(uint time)
{uint a,b;
for(a=0;a<time;a++)
for(b=0;b<2;b++);
}
/********初始化中断函数************/
void timer0_init(void) //初始化
{
TMOD = 0x01;
TH0 = 0xec;
TL0 = 0x78;
TR0 = 1;
EA = 1;
ET0 = 1;
}
/************************************************************************/
void timer0_isr(void) interrupt 1 //中断
{
TH0 = (65535-1000)/256;
TL0 = (65535-1000)%256;
timer++;
}
/**********显示函数************/
void display_num(uint num)
{
BIT1=1;
P2=seven_seg[num/100%10];
BIT2=0;
delay_time(10);
BIT2=1;
P2=seven_seg[num/10%10]+0X01;
BIT3=0;
delay_time(10);
BIT3=1;
P2=seven_seg[num%10];
BIT4=0;
delay_time(10);
BIT4=1;
}
/***********主函数*************/
void main(void)
{
KEY=1;
timer0_init();
while(1)
{
if(KEY==0){temp=0;LED=0;}
display_num(temp); // temp2
if(timer>1000)
{timer=0;temp=Read_Temperature();}
LED=1;
}
}
|
|