📄 ds18b20.c
字号:
/****************************************************************************/
/*
文 件 名: DS18B20.c
说 明: DS18B20驱动程序,
作 者: 郭天祥
日 期: 2008.9
*/
/*****************************************************************************/
#include "..\inc\uTypes.h"
#include "..\inc\sysUtils.h"
#include "..\inc\ds18b20.h"
#include "..\inc\console.h"
#define ESC_KEY 0x1b
//DS18B20的端口为GPF4
#define DS_H() rPDATF|=(1<<4) //端口高
#define DS_L() rPDATF&=~(1<<4) //端口低
#define DS_OUT() rPCONF|=(01<<(4*2));rPCONF&=(01<<(4*2)) //端口为输出
#define DS_IN() rPCONF&=~(11<<(4*2)) //端口为输入
#define DS_R() (rPDATF&(1<<4))
U16 temp; //variable of temperature
/*************************
函数:void DS_Reset(void)
功能:18b20复位
**************************/
void DS_Reset(void) //send reset and initialization command
{
DS_OUT();
DS_L();
sysUtilsUSecDelay(700);
DS_H();
sysUtilsUSecDelay(4);
DS_IN();
sysUtilsUSecDelay(100);
/*if(DS_R()!=0) //测试复位是否成功
printf("There are no 18B20 at GPF4! 0x%x\n");
else
printf("Init 18B20 succeed!\n");*/
sysUtilsUSecDelay(250);//等待低电平过去
}
/*********************************
函数:U8 tmpreadbit(void)
功能:读取18b20的一位数据
**********************************/
U8 tmpreadbit(void)
{
U8 dat;
DS_OUT();
DS_L();
sysUtilsUSecDelay(2);
DS_IN();
sysUtilsUSecDelay(10);
if(DS_R()!=0)
dat=1;
else
dat=0;
sysUtilsUSecDelay(50);
return (dat);
}
/**********************************
函数:U8 tmpread(void)
功能:读取一个字节的数据
***********************************/
U8 tmpread(void)
{
U8 i,j,dat;
dat=0;
for(i=1;i<=8;i++)
{
j=tmpreadbit();
dat=(j<<7)|(dat>>1); //读出的数据最低位在最前面,这样刚好一个字节在DAT里
}
return(dat);
}
/*********************************
函数:void tmpwritebyte(U8 dat)
功能:向18b20写入一个字节数据
**********************************/
void tmpwritebyte(U8 dat)
{
U8 j;
U8 testb;
DS_OUT();
for(j=1;j<=8;j++)
{
testb=dat&0x01;
dat=dat>>1;
if(testb)
{
DS_L();
sysUtilsUSecDelay(8);
DS_H();
sysUtilsUSecDelay(50);
}
else
{
DS_L();
sysUtilsUSecDelay(90);
DS_H();
sysUtilsUSecDelay(8);
}
}
}
void Tmp_Change(void) //DS18B20 begin change
{
DS_Reset();
sysUtilsUSecDelay(2);/*delay(1);*/
tmpwritebyte(0xcc); // address all drivers on bus
tmpwritebyte(0x44); // initiates a single temperature conversion
}
U16 tmp(void) //get the temperature
{
float tt;
U8 a,b;
DS_Reset();
sysUtilsUSecDelay(4);/*delay(1);*/
tmpwritebyte(0xcc);
tmpwritebyte(0xbe);
a=tmpread();
b=tmpread();
temp=b;
temp<<=8; //two byte compose a int variable
temp=temp|a;
tt=temp*0.0625;
temp=tt*10+0.5;
return temp;
}
void readrom(void) //read the serial
{
U8 sn1,sn2;
DS_Reset();
sysUtilsUSecDelay(4);
tmpwritebyte(0x33);
sn1=tmpread();
sn2=tmpread();
}
//18b20测试
void Test_18b20(void)
{
U16 i;
while( !( kbhit() && (getkey()==ESC_KEY)))
{
Tmp_Change();
sysUtilsUSecDelay (5000); //延迟5ms
i=tmp();
printf("Now temperature is %d.%d 'C.\n",i/10,i%10);
sysUtilsUSecDelay (500000); //延迟500ms
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -