武林教你学PIC32(十八)单总线DS18B20温度传感器
扫描二维码
随时随地手机看文章
简单介绍下DS18B20,它是独特的单线接口,仅需一个端口进行通讯9~12位的分辨率可调(RS)测温范围为-55°C~+125°C;测量范围在-10°C ~+85°C精度为±0.5°C可设置报警温度存储于EEPROM,掉电保护数据不丢适用电压3~5.5V
下面介绍我封装好的函数,已经测试可以使用,需要注意的是PORTReadBits,需要根据实际端口相应地移位
DS18B20.H:
#ifndef _DS18B20_H_
#define _DS18B20_H_
#include
#define DQ_PORTIOPORT_D//设置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; //设置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);//读数据,从低位开始 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();//复位18b20 write_1820(0xcc);//发出转换命令 write_1820(0x44); //delay_nms(800);//不延时也好使,不知道怎么回事! init_1820(); write_1820(0xcc);//发出读命令 write_1820(0xbe); teml=read_1820();//读数据 temh=read_1820(); temp=temh; temp<<=8; temp|=teml; value=temp*0.0625; return value; }