PIC单片机控制DS18B20数字温度传感器原理及实现
扫描二维码
随时随地手机看文章
#include #define uchar unsigned char void get_tem()
#define uint unsigned int
#define DQ RC1
#define DQ_HIGH() TRISC1=1
#define DQ_LOW() TRISC1=0;DQ=0
__CONFIG(0x3B31);
const uchar table[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,
0x07,0x7f,0x6f};
const uchar table1[]={0xbf,0x86,0xdb,0xcf,0xe6,0xed,0xfd,
0x87,0xff,0xef};
uint temper;
uchar a1,a2,a3,a4;
void delay(uint x);
void delayus(uint,uchar);
void init();
void disp(uchar num1,uchar num2,uchar num3,uchar num4);
void write_byte(uchar date);
uchar read_byte();
void get_tem();
void main()
{
init();
while(1)
{
/*delayus(0,0);//20
delayus(1,1);//30
delayus(2,2);//45
delayus(4,4);//70
delayus(70,30);//750
delayus(50,10);//500*/
//uchar num;
get_tem();
//for(num=20;num>0;num--)
//disp(a1,a2,a3,a4);
}
}
void reset()
{
uchar st=1;
DQ_HIGH();
NOP();NOP();
while(st)
{
DQ_LOW();
delayus(70,30);
DQ_HIGH();
delayus(4,4);
if(DQ==1)
st=1;
else
st=0;
delayus(50,10);
}
}
void write_byte(uchar date)
{
uchar i,temp;
DQ_HIGH();
NOP();NOP();
for(i=8;i>0;i--)
{
temp=date&0x01;//01010101
DQ_LOW();
delayus(0,0);
if(temp==1)
DQ_HIGH();
delayus(2,2);
DQ_HIGH();
date=date>>1;//00101010
}
}
uchar read_byte()
{
uchar i,date;
static bit j;
for(i=8;i>0;i--)
{
date=date>>1;
DQ_HIGH();
NOP();NOP();
DQ_LOW();
NOP();NOP();NOP();NOP();NOP();NOP();
DQ_HIGH();
NOP();NOP();NOP();NOP();
j=DQ;
if(j==1)
date=date|0x80;//1000 0000
delayus(1,1);
}
return (date);
}
{
uchar tem1,tem2,num;
float aaa;
reset(); //复位
write_byte(0xCC);//跳过ROM
write_byte(0x44);//温度转换
for(num=100;num>0;num--)
disp(a1,a2,a3,a4);
reset();
write_byte(0xCC);
write_byte(0xBE);
tem1=read_byte();
tem2=read_byte();
aaa=(tem2*256+tem1)*6.25;
temper=(int)aaa;
a1=temper/1000;
a2=temper%1000/100;
a3=temper%100/10;
a4=temper%10;
}
void delayus(uint x,uchar y)
{
uint i;
uchar j;
for(i=x;i>0;i--);
for(j=y;j>0;j--);
}
void delay(uint x)
{
uint a,b;
for(a=x;a>0;a--)
for(b=110;b>0;b--);
}
void init()
{
TRISD=0;
TRISA=0;
PORTD=0;
PORTA=0;
}
void disp(uchar num1,uchar num2,uchar num3,uchar num4)
{
PORTD=table[num1];//显示第一个数码管
PORTA=0x20;//0010 0000
delay(2);
PORTD=table1[num2];//显示第二个数码管
PORTA=0x10;//0001 0000
delay(2);
PORTD=table[num3];//显示第三个数码管
PORTA=0x08;//0000 1000
delay(2);
PORTD=table[num4];//显示第四个数码管
PORTA=0x04;//0000 0100
delay(2);
/*PORTD=table[num5];//显示第五个数码管
PORTA=0x02;//0000 0010
delay(2);
PORTD=table[num6];//显示第六个数码管
PORTA=0x01;//0000 0001
delay(2);*/
}