📄 ds18b20.c
字号:
#include <reg52.h>
#define uchar unsigned char
#define uint unsigned int
sbit DS=P2^7; //define interface 定义接口
uint temp; // variable of temperature 定义一个变量用来表示温度
uchar flag1; // sign of the result positive or negative 定义一个标志,标志温度是否还是正
sbit P2_0=P2^0; //数码管位选
sbit P2_1=P2^1;
sbit P2_2=P2^2;
unsigned char code table[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82, //数字编码
0xf8,0x80,0x90};
unsigned char code table1[]={0x40,0x79,0x24,0x30,0x19,0x12,0x02, //带小数点的编码
0x78,0x00,0x10};
void delay(uint count) //delay 延时子程序
{
uint i;
while(count)
{
i=200;
while(i>0)
i--;
count--;
}
}
void dsreset(void) //send reset and initialization command 发送初始化命令子程序
{
uint i;
DS=0;
i=103;
while(i>0)i--;
DS=1;
i=4;
while(i>0)i--;
}
bit tmpreadbit(void) //read a bit 读一位
{
uint i;
bit dat;
DS=0;i++; //i++ for delay
DS=1;i++;i++;
dat=DS;
i=8;while(i>0)i--;
return (dat);
}
uchar tmpread(void) //read a byte date 读一个字节
{
uchar i,j,dat;
dat=0;
for(i=1;i<=8;i++)
{
j=tmpreadbit();
dat=(j<<7)|(dat>>1); //读出的数据最低位在最前面,这样刚好一个字节在DAT里
}
return(dat);
}
void tmpwritebyte(uchar dat) //write a byte to ds18b20 给温度传感器写一个字节
{
uint i;
uchar j;
bit testb;
for(j=1;j<=8;j++)
{
testb=dat&0x01;
dat=dat>>1;
if(testb) //write 1
{
DS=0;
i++;i++;
DS=1;
i=8;while(i>0)i--;
}
else
{
DS=0; //write 0
i=8;while(i>0)i--;
DS=1;
i++;i++;
}
}
}
void tmpchange(void) //DS18B20 begin change 发送温度转换命令
{
dsreset();
delay(1);
tmpwritebyte(0xcc); // address all drivers on bus
tmpwritebyte(0x44); // initiates a single temperature conversion
}
uint tmp() //get the temperature 得到温度值
{
float tt;
uchar a,b;
dsreset();
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() //read the serial 读取温度传感器的序列号子函数
{
uchar sn1,sn2;
dsreset();
delay(1);
tmpwritebyte(0x33);
sn1=tmpread();
sn2=tmpread();
}
void delay10ms() //delay 延时10MS子函数
{
uchar a,b;
for(a=10;a>0;a--)
for(b=60;b>0;b--);
}
void display(uint tem) //display 显示子函数
{
uchar j,A1,A2,A2t,A3;
A1=table[tem/100];
A2t=tem%100;
A2=table1[A2t/10];
A3=table[A2t%10];
// for(j=50;j>0;j--)
// {
P0=A1;
P2_0=0;
P2_1=1;
P2_2=1;
delay10ms();
P0=A2;
P2_1=0;
P2_0=1;
P2_2=1;
delay10ms();
P0=A3;
P2_2=0;
P2_0=1;
P2_1=1;
// }
}
void main() //主函数
{
do
{
tmpchange(); //温度转换,
// delay(200);
display(tmp()); //显示温度值
} while(1);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -