?? 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 + -