|
楼主 |
发表于 2007-6-16 20:08:43
|
显示全部楼层
我没有用UART中断,现经过测试发现液晶显示串行收发都没问题,问题出在18B20的函数,我发现我写的函数不稳定,代码贴这里了,马老师帮忙看一下,谢谢
#define SET_DQ_High P2|=(1<<(n-1))
#define SET_DQ_LOW P2&=~(1<<(n-1))
void delay_ms(uint n)
{
uint i,j;
for(i=n;i>0;i--)
for(j=0;j<1140;j++);
}
void Init_DS18B20(uchar num) //初始化函数
{
uchar x=0;
uchar n;
n=num;
SET_DQ_High;
//DQ = 1; //DQ复位
delay(8); //稍做延时
SET_DQ_LOW;
// DQ = 0; //单片机将DQ拉低
delay(80); //精确延时 大于480us
SET_DQ_High;
// DQ = 1; //拉高总线
delay(14);
x=P2&(1<<(n-1));
// x=DQ; //稍做延时后 如果x=0则初始化成功 x=1则初始化失败
}
////////////////////////////////////////////////////////////////
char ReadOneChar(uchar num) //读一个字节
{
unsigned char i=0;
unsigned char dat = 0;
uchar n;
n=num;
for (i=8;i>0;i--)
{
SET_DQ_LOW;
// DQ = 0; // 给脉冲信号
dat>>=1;
SET_DQ_High;
// DQ = 1; // 给脉冲信号
if((P2&(1<<(n-1)))>>(n-1))
// if(DQ)
dat|=0x80;
delay(4);
}
return(dat);
}
/////////////////////////////////////////////////////////////
void WriteOneChar(uchar dat,uchar num)//写一个字节
{
unsigned char i=0;
uchar n;
n=num;
for (i=8; i>0; i--)
{
SET_DQ_LOW;
// DQ = 0;
if(dat&0x01)
{
P2|=(1<<(n-1));
}
else
P2&=~(1<<(n-1));
// DQ = dat&0x01;
delay(5);
SET_DQ_High;
// DQ = 1;
dat>>=1;
}
delay(4);
}
/////////////////////////////////////////////////////////////
uint ReadTemperature(uchar num) //读取温度
{
unsigned char a=0,c=0; //低字节
unsigned char b=0; //高字节
unsigned int t=0; //温度
uchar n;
n=num;
Init_DS18B20(n);
WriteOneChar(0xCC,n); // 跳过读序号列号的操作
WriteOneChar(0x44,n); // 启动温度转换
Init_DS18B20(n);
WriteOneChar(0xCC,n); //跳过读序号列号的操作
WriteOneChar(0xBE,n); //读取温度寄存器等(共可读9个寄存器)前两个就是温度
a=ReadOneChar(n); //Read the low byte of the temperature
b=ReadOneChar(n); // high
c=a;
a>>=4; //低字节右移四位
b<<=4; //高字节左移四位
t=a|b;
t<<=8;
c&=0x0F;
t|=c;
// tt=c;
// tt*=0.0625;
// c=tt*10+0.5;
// t=t*10+c;
return t;
}
/////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
void delay10ms(unsigned char time) //延时程序
{
uchar a,b,c;
for(a=0;a<time;a++)
for(b=0;b<10;b++)
for(c=0;c<12;c++);
}
///////////////////////////////////////////////////////////////
void delay(unsigned int i)//延时函数
{
while(i--);
} |
|