武林教你學(xué)PIC32(十八)單總線DS18B20溫度傳感器
簡(jiǎn)單介紹下DS18B20,它是獨(dú)特的單線接口,僅需一個(gè)端口進(jìn)行通訊9~12位的分辨率可調(diào)(RS)測(cè)溫范圍為-55°C~+125°C;測(cè)量范圍在-10°C ~+85°C精度為±0.5°C可設(shè)置報(bào)警溫度存儲(chǔ)于EEPROM,掉電保護(hù)數(shù)據(jù)不丟適用電壓3~5.5V
下面介紹我封裝好的函數(shù),已經(jīng)測(cè)試可以使用,需要注意的是PORTReadBits,需要根據(jù)實(shí)際端口相應(yīng)地移位
DS18B20.H:
#ifndef _DS18B20_H_
#define _DS18B20_H_
#include
#define DQ_PORTIOPORT_D//設(shè)置DQ引腳
#define DQ_PINBIT_14
#define SET_OP_1WIREPORTSetBits(DQ_PORT, DQ_PIN)
#define CLR_OP_1WIREPORTClearBits(DQ_PORT, DQ_PIN)
#define SET_DIR_1WIREPORTSetPinsDigitalOut(DQ_PORT, DQ_PIN)
#define CLR_DIR_1WIREPORTSetPinsDigitalIn(DQ_PORT, DQ_PIN)
#define CHECK_IP_1WIREPORTReadBits(DQ_PORT, DQ_PIN)>>14
extern void delay_us(unsigned int num);
extern void delay_ms(unsigned int num);
float gettemp(void);//讀取溫度值
#endif
DS18B20.C
#include "ds18b20.h"
void init_1820()
{
SET_DIR_1WIRE; //設(shè)置PC2為輸出
SET_OP_1WIRE;
CLR_OP_1WIRE;
delay_us(480);//480us以上
SET_OP_1WIRE;
CLR_DIR_1WIRE;
delay_us(20);//15~60us
while(CHECK_IP_1WIRE);
SET_DIR_1WIRE;
SET_OP_1WIRE;
delay_us(140);//60~240us
}
void write_1820(unsigned char x)
{
unsigned char m;
for(m=0;m<8;m++)
{
CLR_OP_1WIRE;
if(x&(1< SET_OP_1WIRE; else {CLR_OP_1WIRE;} delay_us(40);//15~60us SET_OP_1WIRE; } SET_OP_1WIRE; } unsigned char read_1820() { unsigned char temp,k,n; temp=0; for(n=0;n<8;n++) { CLR_OP_1WIRE; SET_OP_1WIRE; CLR_DIR_1WIRE; k=(CHECK_IP_1WIRE);//讀數(shù)據(jù),從低位開始 if(k) temp|=(1< else temp&=~(1< delay_us(50); //60~120us SET_DIR_1WIRE; } return (temp); } float gettemp()//讀取溫度值 { unsigned char temh,teml; unsigned int temp; float value; init_1820();//復(fù)位18b20 write_1820(0xcc);//發(fā)出轉(zhuǎn)換命令 write_1820(0x44); //delay_nms(800);//不延時(shí)也好使,不知道怎么回事! init_1820(); write_1820(0xcc);//發(fā)出讀命令 write_1820(0xbe); teml=read_1820();//讀數(shù)據(jù) temh=read_1820(); temp=temh; temp<<=8; temp|=teml; value=temp*0.0625; return value; }