📄 18b20.c
字号:
#include"reg51.h"
#include"intrins.h"
#define uchar unsigned char
#define uint unsigned int
#define dis_show P0
#define dis_con P2
sbit DS=P3^7;
sbit DIN=P1^7;
//sbit P1_6=P1^6;
uchar code dis_7[11]={0x18,0xde,0x34,0x94,0xd2,0x91,0x11,0xd8,0x10,0x90,0xf7};//数码管0~9,不亮 ,-
uchar code scan_con[2]={0xfe,0xfd};//列扫描
uchar data temp_data[2] ={0x01,0x91}; //读出温度暂存单元 ={0x50,0x05}; 高位存高位 低位存低位
uchar data dis_data[5];
void delay(uint t)
{
for(;t>0;t--);//循环一次延时11us
}
//18b20复位程序
void reset()
{
uint h;
bit flag=1;
while(flag)
{
while(flag)
{
DS=1;
_nop_(); _nop_(); _nop_();
DS=0;//以上程序段制造一个下降延
delay(50);//延时550us 最短延时480us
DS=1;//18b20在上升延后等待15~60us发出存在脉冲,低电平持续60~240us 复位成功
delay(3);
flag=DS;
}
delay(50);//延时550us 看电平能不能升高 如果能升高证明是 低电平脉冲
DS=1;
flag=~DS;
}
}
//18b20写命令函数
void write(uchar rule)
{
uchar i,temp;
for(i=0;i<8;i++)
{
temp=rule&0x01;
DS=1;
_nop_(); _nop_(); _nop_();
DS=0;//以上程序段制造一个下降延
_nop_(); _nop_(); _nop_();
DS=temp;//从低位起 按位取出 送给18B20
rule=rule>>1;
delay(6);//延时66us
}
DS=1;
delay(1);
}
//读一温度字节
uchar read()
{
uchar data i;
uchar data temp=0x00;
uchar data value=0;
for(i=0;i<8;i++)
{
DS=1;
_nop_(); _nop_(); _nop_();
DS=0;//以上程序段制造一个下降延
_nop_(); _nop_(); _nop_();
DS=1;
_nop_(); _nop_(); _nop_();
value>>=1;
DS=0;
_nop_(); _nop_(); _nop_(); _nop_();
DS=1;
_nop_(); _nop_(); _nop_(); _nop_();
if(DS) value|=0x80;
delay(6);
}
DS=1;
return(value);
}
//读出温度函数
read_temp()
{ uchar h;
reset();
write(0xcc);//发skiprom命令
write(0xbe); //读命令
temp_data[0]=read();
for(h=0;h<50;h++)
display(); //多加了一次显示 为了解决在显示过程中因为数据处理时间过长引
temp_data[1]=read(); //引起的显示眨眼问题
reset();
write(0xcc);//发skiprom命令
write(0x44);//发送转换命令
}
//数据处理函数
deal_data()
{
uchar data tmp[2];
if(temp_data[1]>127) //判断小于零
{
temp_data[1]=~temp_data[1]+1;
temp_data[0]=~temp_data[0]+1;
dis_data[0]=0xbf;
}
tmp[1]=temp_data[1]<<4;
tmp[2]=temp_data[0]>>4;
tmp[2]=tmp[2]&0x0f;
tmp[1]=tmp[1]|tmp[2];//整数部分
tmp[0]=temp_data[0]&0x0f; //小数部分
//dis_data[1]=tmp[1]/100; //百位
dis_data[1]=tmp[1]%100/10;
dis_data[2]=tmp[1]%10; //dis_data[0--3]内容是“-” 高位到低位
//dis_data[3]=tmp[0]/2 ; //小数点后只是0到8 没有 9
}
///显示扫描函数
display()
{
uchar i;
// dis_show=dis_data[0];
// dis_con=scan_con[0];
// delay(100);
for(i=1;i<3;i++)
{
dis_show=dis_7[dis_data[i]];
dis_con=scan_con[2-i];
//if(i==1) DIN=0;
delay(400);
}
}
//主函数
void main()
{
uint h;
EA=0;
reset();
write(0xcc);//发skiprom命令
write(0x44);//发送转换命令
for(h=0;h<100;h++)
display();
while(1)
{
read_temp();
deal_data();
for(h=0;h<100;h++)
display();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -