#include"pic.h"
#define uchar unsigned char
#define DQ RB0
static unsigned char tab[]=
{0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};
unsigned char word[4];
void delay(unsigned int i)
{
while(i--);
}
void delay_ms(unsigned int i)
{
unsigned int j;
for(i;i>0;i--)
for(j=0;j<90;j++);
}
void display()
{
unsigned char t=0xfe,i=0;
for(i=0;i<4;i++)
{
PORTD=t;
if(i==2)
{PORTC=tab[word];
PORTC|=0x80;
}
else
PORTC=tab[word];
t=(t<<1)|0x01;
if(t==0xef) t=0xfe;
delay_ms(1);
}
}
void init_ds18b20()
{
unsigned char j=1;
while(j)
{
TRISB0=0;
DQ=0;
delay(64);
DQ=1;
delay(5);
TRISB0=1;
if (DQ)
j=1; //若DS18B20无应答,循环检查
else
j=0; //检测到DS18B20应答低电平信号
delay(43);
}
}
unsigned char ReadOneChar()
{
unsigned char i=0,dat=0;
for(i=8;i>0;i--)
{
TRISB0=0;
DQ=0;
dat>>=1;
DQ=1;
TRISB0=1;
NOP();NOP();
if(DQ==1)
dat|=0x80;
delay(5);
}
return dat;
}
void WriteOneChar(unsigned char dat)
{
unsigned char i=0,tmp;
for(i=8;i>0;i--)
{
tmp=dat&0x01;
dat>>=1;
if (tmp) //tmp=1时
{
TRISB0=0;
DQ=0;
NOP();NOP();
DQ=1;
TRISB0=1;
delay(5); //延时61us
}
else
{
TRISB0=0;
DQ=0;
delay(5); //延时61us
DQ=1;
TRISB0=1;
NOP();NOP();
}
}
}
void ReadTemperature()
{
unsigned char a,b;
int temp;
init_ds18b20();
WriteOneChar(0xcc);
WriteOneChar(0x44);
init_ds18b20();
WriteOneChar(0xcc);
WriteOneChar(0xbe);
a=ReadOneChar();
b=ReadOneChar();
temp=b*256+a;
temp>>=4;
word[0]=temp/100;
word[1]=((temp/10)%10);
word[2]=temp%10;
word[3]=0;
}
void main()
{
TRISC=0;
TRISD=0;
while(1)
{
ReadTemperature();
display();
}
}
友情提示: 此问题已得到解决,问题已经关闭,关闭后问题禁止继续编辑,回答。
一周热门 更多>