/**************************************
** Filename: 18b20.c
** Describe: 18b20 温度传感器
** Author : 古欣 www.avrvi.com
** Time : 2007-2-15
**************************************/
#include "config.h"
unsigned char wmh,wml,flag,count; //flag温度为负标志,count为实际温度
void init_1820(void)
{
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<<m)) //写数据了,先写低位的!
SET_OP_1WIRE;
else
{CLR_OP_1WIRE;}
delay_us(40); //15~60us
SET_OP_1WIRE;
}
SET_OP_1WIRE;
}
unsigned char read_1820(void)
{
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<<n);
else
temp&=~(1<<n);
delay_us(50); //60~120us
SET_DIR_1WIRE;
}
return (temp);
}
void gettemp(void) //读取温度值
{
unsigned char temh,teml,wm0,wm1,wm2,wm3;
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();
wm0=teml>>4; //只要高8位的低四位和低8位的高四位,温度范围0~99啦!
wm1=temh<<4;
//count=(temh*256+teml)*6.25; //计算具体温度
if((temh&0xF8) == 0xF8)
{
flag=1;
count=((0xFF-temh)*256+(0xFF-teml))*6.25;
//count=((0xFF-temh)*256+(0xFF-teml))*625;
}
else
{
flag=0;
count=(temh*256+teml)*6.25;
//count=(temh*256+teml)*625; //计算具体温度
}
wm2=wm1+wm0; //16进制转10进制
wm3=wm2/100;
wmh=(wm2%100)/10; //出口参数了!wmh是显示的高位,wml是显示的低位
wml=(wm2%100)%10;
}
http://bbs.avrvi.com/simple/t1485.html |