DS18B20的驱动程序
扫描二维码
随时随地手机看文章
/********************************************************************
程序名称:DS18B20演示实验
时钟频率:内部RC 8M
芯片 :DS18B20
引脚 :**PA0 DATA**
**PD0--PD7接数码管扫描端1--8**
**PC0--PC7接数码管扫描端。.A--G**
********************************************************************/
#include
#include
#define DQ_H PORTA|=BIT(PA0);
#define DQ_L PORTA&=~BIT(PA0);
#define DQ_IN (PINA&0X01);
#define true 1
#define false 0
unsigned int m,i=0, temp,lsb,msb,num;
const unsigned char f[]=
{
0x7e,0x0c,0xb6,0x9e,0xcc,0xda,0xfa,0x0e,0xfe,0xde,0xee,0xf8,0x72,0xbc,0xf2,0xe2
};//码段字型
voidDelay(unsigned int k)//延时
{
do
{
k--;
}
while(k>1);
}
void saomiao(void)//数码管扫描
{
PORTC=f[m%10];
PORTD=0xfe;
Delay(900);
PORTC=f[m/10%10];
PORTD=0xfd;
Delay(900);
PORTC=f[m/100%10];
PORTD=0xfb;
Delay(900);
PORTC=0x01;
PORTD=0xf7;//小数点
Delay(900);
PORTC=f[m/1000%10];
PORTD=0xf7;
Delay(900);
PORTC=f[m/10000%10];
PORTD=0xef;
Delay(900);
PORTC=0x00;
PORTD=0xff;
Delay(900);
}
unsigned char ds1820_reset(void)//复位
{
unsigned char ack;
DDRA |=BIT(PA0);
DQ_L;
Delay(480);
DQ_H;
DDRA &= ~BIT(PA0);
Delay(45);
ack = DQ_IN;
Delay(420);
if(ack)
return true;
else
return false;
}
unsigned chards18b20_read_byte(void)//读一字节
{
unsigned chari,num;
unsigned charvalue = 0;
for(i = 8; i > 0; i--)
{
value >>= 1;
DDRA |= BIT(PA0);
DQ_L;
Delay(16);
DQ_H;
DDRA &= ~BIT(PA0);
Delay(10);
num=DQ_IN;
if(num)
value|=0x80;
Delay(100);
DDRA|= BIT(PA0);
Delay(5);
}
return(value);
}
voidds18b20_write_byte(unsigned char value)//写一字节
{
unsigned chari;
DDRA|= BIT(PA0);
for(i = 8; i > 0; i--)
{
if(value & 0x01)
{
DQ_L;
Delay(10);
DQ_H;
Delay(100);
}
else
{
DQ_L;
Delay(100);
DQ_H;
Delay(10);
}
value >>= 1;
}
}
unsigned intwendu()//读取温度值
{
unsigned char i;
unsigned int TEMP;
unsigned charTEMP_LSB,TEMP_MSB;
ds1820_reset();
ds18b20_write_byte(0xCC);//跳过ROM
ds18b20_write_byte(0x44);//启动一次转换
for(i = 0; i < 16; i++)
saomiao();//插入扫描
saomiao();
saomiao();
saomiao();
saomiao();
saomiao();
saomiao();
saomiao();
ds1820_reset();
ds18b20_write_byte(0xCC);//跳过ROM
ds18b20_write_byte(0xBE);//读取温度
TEMP_LSB = ds18b20_read_byte();
TEMP_MSB = ds18b20_read_byte();
TEMP=TEMP_MSB;
TEMP=TEMP<<8;
TEMP=TEMP|TEMP_LSB;
return(TEMP);
}
const unsigned char g[]=
{
0, 63, 130, 188, 250, 313,375,438,500, 563,625,688,750,813,875,938
};//小数点后数据转换(减少运算负担)
void main(void)//主程序
{
DDRD=0xff;
DDRC=0xff;
PORTD=0;
PORTC=0;
while(1)
{
num=wendu();
temp=(num>>8)&0xf0;
if(temp==0xf0)
{
num=(~num)+1;
i=num&0x0f;
lsb=g[i];
msb=(num>>4)&0xff;
}
else
{
i=num&0x0f;
lsb=g[i];
msb=(num>>4)&0xff;
}
m=msb*1000+lsb;
for (i=0;i<6;i++)
{
saomiao();
}
}
}