这是ds18b20.c的:
#include "ds18b20.h"
#include "reg52.h"
sbit DQ=P1^4;
void Delay_OneWire(unsigned int t)
{
unsigned char i;
while(t--){
for(i=0;i<12;i++);
}
}
void Write_DS18B20(unsigned char dat)
{
unsigned char i;
for(i=0;i<8;i++)
{
DQ = 0;
DQ = dat&0x01;
Delay_OneWire(5);
DQ = 1;
dat >>= 1;
}
Delay_OneWire(5);
}
unsigned char Read_DS18B20(void)
{
unsigned char i;
unsigned char dat;
for(i=0;i<8;i++)
{
DQ = 0;
dat >>= 1;
DQ = 1;
if(DQ)
{
dat |= 0x80;
}
Delay_OneWire(5);
}
return dat;
}
unsigned char init_ds18b20(void)
{
unsigned char initflag = 0;
DQ = 1;
Delay_OneWire(12);
DQ = 0;
Delay_OneWire(80);
DQ = 1;
Delay_OneWire(10);
initflag = DQ;
Delay_OneWire(5);
return initflag;
}
float read_ds18b20_temp()
{
unsigned char ls;
unsigned int hs;
init_ds18b20();
Write_DS18B20(0xcc);
Write_DS18B20(0x44);
Delay_OneWire(1000);
init_ds18b20();
Write_DS18B20(0xcc);
Write_DS18B20(0xbe);
ls=Read_DS18B20();
hs=Read_DS18B20();
return ((hs<<8)|ls)/16.0;
}
这是主程序:
#include "reg52.h"
#include "ds18b20.h"
unsigned char smgdata[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0x88,0x83,0xc6,0xa1,0x86,0x8e,0xbf,0x8c};
float temp;
void selecthc573(unsigned char a)
{
switch(a)
{
case 4: P2=(P2&0x1f)|0x80;break;
case 5: P2=(P2&0x1f)|0xa0;break;
case 6: P2=(P2&0x1f)|0xc0;break;
case 7: P2=(P2&0x1f)|0xe0;break;
}
}
void seg_dy(unsigned char wei,duan,point)
{
P0=0xff;
if(point)
{
selecthc573(7);
P0=duan&0x7f;
P2&=0x1f;
}
else
{
selecthc573(7);
P0=duan;
P2&=0x1f;
}
selecthc573(6);
P0=0x01<<wei;
P2&=0x1f;
}
void delay(int s)
{
while(s--);
}
void segdisplay()
{
temp=read_ds18b20_temp();
seg_dy(0,smgdata[((unsigned char)temp/10%10)],0);
delay(600);
seg_dy(1,smgdata[((unsigned char)temp%10)],1);
delay(600);
seg_dy(2,smgdata[((unsigned int)(temp*10)%10)],0);
delay(600);
}
int main()
{
while(1)
{
segdisplay();
}
}
|