1、初始化
2、ROM指令
3、寄存器指令
注意:官方提供的初始化驱动应延时500微妙,读写驱动应延时80微妙
#include <reg52.h>
#include <intrins.h>
#define uchar unsigned char
#define uint unsigned int
sbit DQ = P1^4;
uchar code tab_duan[] = {0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,\
0x40,0x79,0x24,0x30,0x19,0x12,0x02,0x78,0x00,0x10,0xbf,0xff};
uchar yi,er,san,si,wu,liu,qi,ba;
long wendu;
void All_Init();
void Delay1ms();
void Delay500us();
void Delay80us();
void Display1(uchar yi,uchar er);
void Display2(uchar san,uchar si);
void Display3(uchar wu,uchar liu);
void Display4(uchar qi,uchar ba);
void init_ds18b20(void);
unsigned char Read_DS18B20(void);
void Write_DS18B20(unsigned char dat);
long TemperGet();
void main()
{
All_Init();
yi=21;er=21;san=21;si=21;wu=21;liu=21;qi=21;ba=21;
while(1)
{
wendu = TemperGet();
yi=wendu/100000;er=wendu%100000/10000+10;san=wendu%10000/1000;si=wendu%1000/100;
Display1(yi,er);
Display2(san,si);
Display3(wu,liu);
Display4(qi,ba);
}
}
//DS18B20设备初始化
void init_ds18b20(void)
{
DQ = 0;
Delay500us();
DQ = 1;
Delay500us();
}
void Delay80us() //@11.0592MHz
{
unsigned char i, j;
_nop_();
i = 1;
j = 217;
do
{
while (--j);
} while (--i);
}
//通过单总线向DS18B20写一个字节
void Write_DS18B20(unsigned char dat)
{
unsigned char i;
for(i=0;i<8;i++)
{
DQ = 0;
DQ = dat&0x01;
Delay80us();
DQ = 1;
dat >>= 1;
}
}
//从DS18B20读取一个字节
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 == 1)
{
dat |= 0x80;
}
Delay80us();
}
return dat;
}
void Delay500us() //@11.0592MHz
{
unsigned char i, j;
_nop_();
_nop_();
i = 6;
j = 93;
do
{
while (--j);
} while (--i);
}
long TemperGet()
{
uchar low,high;
long temp;
init_ds18b20();
Write_DS18B20(0xcc);//忽略ROM指令
Write_DS18B20(0x44);//直接温度转换
Delay500us();
init_ds18b20();
Write_DS18B20(0xcc);//忽略ROM指令
Write_DS18B20(0xbe);//读寄存器指令
//Delay500us();
low = Read_DS18B20();
high = Read_DS18B20();
temp = (high&0x0f);
temp <<=8;
temp|=low;
temp = temp*625;
return temp;
}
void All_Init()
{
P2=0xa0;P0=0x00;//关闭蜂鸣器,继电器
P2=0x80;P0=0xff;//关闭小灯
P2=0xc0;P0=0xff;//选中8个数码管
P2=0xe0;P0=0xff;//关闭选中的8个数码管
}
void Delay1ms() //@11.0592MHz
{
unsigned char i, j;
_nop_();
_nop_();
_nop_();
i = 11;
j = 190;
do
{
while (--j);
} while (--i);
}
void Display1(uchar yi,uchar er)
{
P2=0xc0;
P0=0x01;
P2=0xe0;
P0=tab_duan[yi];
Delay1ms();
P2=0xc0;
P0=0x02;
P2=0xe0;
P0=tab_duan[er];
Delay1ms();
}
void Display2(uchar san,uchar si)
{
P2=0xc0;
P0=0x04;
P2=0xe0;
P0=tab_duan[san];
Delay1ms();
P2=0xc0;
P0=0x08;
P2=0xe0;
P0=tab_duan[si];
Delay1ms();
}
void Display3(uchar wu,uchar liu)
{
P2=0xc0;
P0=0x10;
P2=0xe0;
P0=tab_duan[wu];
Delay1ms();
P2=0xc0;
P0=0x20;
P2=0xe0;
P0=tab_duan[liu];
Delay1ms();
}
void Display4(uchar qi,uchar ba)
{
P2=0xc0;
P0=0x40;
P2=0xe0;
P0=tab_duan[qi];
Delay1ms();
P2=0xc0;
P0=0x80;
P2=0xe0;
P0=tab_duan[ba];
Delay1ms();
}