11.jpg (535.11 KB, 下載次數: 36)
下載附件
2023-7-24 14:35 上傳
#include <reg52.h>
#include <intrins.h>
typedef unsigned char u8;
typedef unsigned int u16;
typedef signed int s16;
sbit IO_18B20=P3^7;
sbit add_1=P2^2;
sbit add_2=P2^3;
sbit add_3=P2^4;
u8 DQ;
u8 c[8];
u8 code a[10]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};//0-9
void Delay_ms(unsigned char ms)//定時器延時函數
{
unsigned char T=0;
TMOD=0x01;
TH0=0xfb;
TL0=0x80;
TR0=1;
while(T<ms)
{
if(TF0==1)
{
TF0=0;
TH0=0xfb2 ;
TL0=0x80;
T++;
}
}
}//1.25*ms
void Delay(u16 i)//延時
{
while(i--);
}
void init_18B20()//DS18B20初始化
{
IO_18B20=0;
Delay(100);
IO_18B20=1;
Delay(5);
DQ=IO_18B20;
Delay(80);
}
void write_cmd(u8 cmd)//DS18B20寫時序
{
u8 i;
for(i=0;i<8;i++)
{
IO_18B20=0;
_nop_();
IO_18B20=cmd&0x01;
Delay(6);
IO_18B20=1;
cmd>>=1;
}
}
u8 read_cmd()//DS18B20讀時序
{
u8 j,by,byte;
for(j=0;j<8;j++)
{
IO_18B20=0;
_nop_();
IO_18B20=1;
_nop_();
_nop_();
by=IO_18B20;
byte=(byte>>1)|(by<<7);
Delay(4);
}
return byte;
}
void change_temper()//溫度轉換
{
init_18B20();
if(DQ==0)
{
write_cmd(0xcc);//跳過ROM
write_cmd(0x44);//溫度轉換后存儲在暫存寄存器的2個字節長度的溫度寄存器中
}
}
void read_temper()//讀溫度
{
init_18B20();
if(DQ==0)
{
write_cmd(0xcc);//跳過ROM
write_cmd(0xbe);//讀取暫存寄存器
}
}
s16 DS18B20temp_data()//采集DS18B20中cache溫度數據
{
s16 temp;
u8 temph,templ;
change_temper();
read_temper();
templ=read_cmd();
temph=read_cmd();
temp=temph;
temp<<=8;
temp|=templ;
return temp;
}
void datapros(s16 temp)//將采集的數據按照規定的分辨率轉化為數字
{
float tp;
if(temp<0)
{
c[0]=0x40;
temp=~temp;
temp+=1;
tp=temp;
temp=tp*0.0625*100+0.5;
}
else
{
c[0]=0x00;
tp=temp;
temp=tp*0.0625*100+0.5; //0.0625為分辨率 100:保留兩位小數 0.5:精度
}
c[1] = a[temp/1000%10];//顯示溫度十位
c[2] = a[temp/100%10]+0x80;//顯示溫度個位
c[3] = a[temp/10%10];//顯示一位小數
}
void shuaxin()//刷新數碼管
{
add_1=0;
add_2=0;
add_3=0;
P0=0x39; //數碼管顯示 C
Delay_ms(1);
P0=0x00;
add_1=1;
add_2=0;
add_3=0;
P0=c[3];
Delay_ms(1);
P0=0x00;
add_1=0;
add_2=1;
add_3=0;
P0=c[2];
Delay_ms(1);
P0=0x00;
add_1=1;
add_2=1;
add_3=0;
P0=c[1];
Delay_ms(1);
P0=0x00;
add_1=0;
add_2=0;
add_3=1;
P0=c[0];
Delay_ms(1);
P0=0x00;
}
void main()//主函數 ---顯示
{
while(1)
{
datapros(DS18B20temp_data());
shuaxin();
}
}
|