|
这是我的程序,显示的时候正负温度可以显示0到8然后就显示不出来了开始乱码,之后到20°之后又正确了是为什么呢?求求帮帮我!谢谢
#include"reg52.h"
#define uchar unsigned char
#define uint unsigned int
sbit DQ=P2^4; //温度数据口
sbit set=P3^0;
sbit add=P3^1;
sbit dec=P3^2;
sbit wx1=P0^0; //位选1
sbit wx2=P0^1; //位选2
sbit wx3=P0^2; //位选3
sbit wx4=P0^3; //位选4
sbit wx5=P0^4; //位选5
sbit wx6=P0^5; //位选6
int fg;
unsigned int temp, temp1,temp2, xs,t;
uchar code table[]={0xc0,0xf9,0xa4,0xb0,0x99,
0x92,0x82,0xf8,0x80,0x90};
/******延时程序*******/
void delay1(unsigned int m)
{
unsigned int i,j;
for(i=m;i>0;i--)
for(j=110;j>0;j--);
}
void delay(unsigned int m) //温度延时程序
{
for(m;m>0;m--);
}
void Init_DS18B20(void)
{
unsigned char x=0;
DQ = 1; //DQ复位 ds18b20通信端口
delay(8); //稍做延时
DQ = 0; //单片机将DQ拉低
delay(80); //精确延时 大于 480us
DQ = 1; //拉高总线
delay(4);
x=DQ; //稍做延时后 如果x=0则初始化成功 x=1则初始化失败
delay(20);
}
/***********ds18b20读一个字节**************/
uchar ReadOneChar(void)
{
unsigned char i=0;
unsigned char dat = 0;
for (i=8;i>0;i--)
{ DQ=1;
delay(1);
DQ = 0; // 高电平拉成低电平时读周期开始
dat>>=1;
DQ = 1; // 给脉冲信号
if(DQ)
dat|=0x80; //
delay(4);
}
return(dat);
}
/*************ds18b20写一个字节****************/
void WriteOneChar(unsigned char dat)
{
unsigned char i=0;
for (i=8; i>0; i--)
{
DQ = 0; //从高电平拉至低电平时,写周期的开始
DQ = dat&0x01; //数据的最低位先写入
delay(5); //60us到120us延时
DQ = 1;
dat>>=1; //从最低位到最高位传入
}
delay(4);
}
/**************读取ds18b20当前温度************/
int ReadTemperature()
{
unsigned char a=0;
unsigned char b=0;
float tt=0;
Init_DS18B20();
WriteOneChar(0xCC); // 跳过读序号列号的操作/
WriteOneChar(0x44); // 启动温度转换
delay(125); // this message is wery important
Init_DS18B20();
WriteOneChar(0xCC); //跳过读序号列号的操作
WriteOneChar(0xBE); //读取温度寄存器等(共可读9个寄存器) 前两个就是温度/
a=ReadOneChar(); //读取温度值低位 /
b=ReadOneChar(); //读取温度值高位 /
t=b;
t<<=8;
t=t|a;
if((t&0x80)!=0)
{
t=~(t-1);
t=t*0.0625*100;
}
else
{
t=t*0.0625*100;
}
return t;
}
void keyscan()
{
}
void wenduxianshi()
{
wx3=1;
P1=table[t/1000]; //显示百位
delay1(5);
wx3=0;
wx4=1;
P1=table[t/100%10]+0x80; //显示十位 加上0x80就显示小数点了。
delay1(5);
wx4=0;
wx5=1;
P1=table[t%100/10]; //显示小数第一位
delay1(5);
wx5=0;
wx6=1;
P1=table[t%10]; //显示小数第二位
delay1(5);
wx6=0;
}
void main()
{
while(1)
{
ReadTemperature();
delay(500);
wenduxianshi();
}
}
|
|