微波EDA网,见证研发工程师的成长!
首页 > 硬件设计 > 嵌入式设计 > 基于C8051F的18B20程序

基于C8051F的18B20程序

时间:12-01 来源:互联网 点击:
#include "C8051F410.h"

#include
#define uint unsigned int
#define uchar unsigned char

sbit DQ = P2^4 ;

void delay(unsigned int i)
{
while(i--);
}
Init_DS18B20(void)
{
unsigned char x=0;
DQ = 1; //DQ复位
delay(176); //稍做延时
DQ = 0; //单片机将DQ拉低
delay(1760); //精确延时 大于 480us
DQ = 1; //拉高总线
delay(308);
x=DQ; //稍做延时后 如果x=0则初始化成功 x=1则初始化失败
delay(440);
}

uchar ReadOneChar(void)
{
unsigned char i=0;
unsigned char dat = 0;
for (i=8;i>0;i--)
{
DQ = 0; // 给脉冲信号
dat>>=1;
DQ = 1; // 给脉冲信号
if(DQ)
dat|=0x80;
delay(88);
}
return(dat);
}

WriteOneChar(unsigned char dat)
{
unsigned char i=0;
for (i=8; i>0; i--)
{
DQ = 0;
DQ = dat&0x01;
delay(110);
DQ = 1;
dat>>=1;
}
}

uint ReadTemperature(void) //温度*10
{
uchar a=0;
uchar b=0;
uint temp=0;
uint t=0;
int temple; /*存放读取的温度值 将其除以16即为得到的值*/
Init_DS18B20();
WriteOneChar(0xCC); // 跳过读序号列号的操作
WriteOneChar(0x44); // 启动温度转换
Init_DS18B20();
WriteOneChar(0xCC); //跳过读序号列号的操作
WriteOneChar(0xBE); //读取温度寄存器等(共可读9个寄存器) 前两个就是温度
a=ReadOneChar(); //低8位
b=ReadOneChar(); //高8位
temp=b;
temp<=8;
temp=temp|a;
temp&=0x07ff;
if( (b&0x08))
{
temple=~temp+1; //如果为负温则去除其补码
FWD=0; /*表示温度为负数*/
}
else
{
temple=temp;
FWD=1; /*表示温度为正数*/
}
t=temple*10/16;
//t = temp;
//t= t*625;
//t = t/1000;
return(t);
}

Copyright © 2017-2020 微波EDA网 版权所有

网站地图

Top