📄 ds18b20.c
字号:
#include <iom16.h>
#include<intrinsics.h>
#define uchar unsigned char
#define uint unsigned int
void init_1820(void)
{
uchar i;
uint j=0;
PORTC|=(1<<7); //"1"
PORTC&=~(1<<7); //"0"
for(i=0;i<8;i++)delay_60us();//480us以上
PORTC|=(1<<7); //"1"
DDRC&=~(1<<7); //"PINC7 is INPUT"
delay_15us(); //15~60us
delay_15us();
Flag_1820Error=0;
while(PINC&(1<<7))
{ delay_60us();
j++;
if(j>=18000){Flag_1820Error=1;break;}
}
DDRC|=(1<<7); //PORTC7 is OUTPUT
PORTC|=(1<<7); //"1"
for(i=0;i<4;i++)delay_60us(); //240us
}
/********************************/
void delay_5us(void) //5us左右
{
uchar x=7;
while(x)
{
x--;
}
}
/*********************************/
void delay_15us(void) //15us左右
{
uchar x=27;
while(x)
{
x--;
}
}
/********************************/
void delay_60us(void) //60us左右
{
uchar x=117;
while(x)
{
x--;
}
}
/********************************/
void write_1820(uchar x)
{
uchar m;
for(m=0;m<8;m++)
{
if(x&(1<<m)) //写数据,从低位开始
{PORTC&=~(1<<7);delay_5us(); //"0",5us
PORTC|=(1<<7); //write"1"
delay_15us(); //15~45us
delay_15us();
delay_15us();
}
else
{PORTC&=~(1<<7);delay_15us();//"0",15us
delay_15us(); //write"0"
delay_15us(); //15~45us
delay_15us();
PORTC|=(1<<7); //"1"
}
}
PORTC|=(1<<7); //"1"
}
/*******************************/
uchar read_1820(void)
{
uchar temp,k,n;
temp=0;
for(n=0;n<8;n++)
{
PORTC&=~(1<<7); //"0"
delay_5us();
PORTC|=(1<<7); //"1"
delay_5us();
DDRC&=~(1<<7); //"PINC7 is INPUT"
k=(PINC&(1<<7)); //读数据,从低位开始
if(k)
temp|=(1<<n); //read"1"
else
temp&=~(1<<n); //read"0"
delay_15us(); //45us
delay_15us();
delay_15us();
DDRC|=(1<<7); //PORTC7 is OUTPUT
}
return (temp);
}
/*************************************/
void read_temperature(void)
{
uchar tempval;
init_1820(); //复位18b20
write_1820(0xcc); // 发出转换命令
write_1820(0x44);
Delay_nms(100);
init_1820();
write_1820(0xcc); //发出读命令
write_1820(0xbe);
teml=read_1820(); //读数据byte1
temh=read_1820(); //byte2
if(temh&0xf8)sign=0;
else sign=1;
if(sign==0){temh=255-temh;teml=255-teml;}
temh=temh<<4;
temh|=(teml&0xf0)>>4;
teml=teml&0x0f;
teml=(teml*10)/16;
tempval=temh;e[0]=tempval/100;
tempval=temh;e[1]=(tempval/10)%10;
tempval=temh;e[2]=tempval%10;
tempval=teml;e[3]=tempval;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -