?? 18b20led.c
字號:
#include <reg52.H>
//----------------------------------------------------------------------------------------------------------------
#define uint unsigned int
#define uchar unsigned char
//----------------------------------------------------------------------------------------------------------------
sbit DQ = P0^0; // 定義DS18B20數據線
sbit BEEP = P0^2; //蜂鳴器
sbit SWH = P0^1;
uchar code dis_7[10]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};
void delay(uint t)
{
while(t--)
;
}
void Init_DS18B20(void)//初始化ds1820
{
uchar x=0;
DQ = 1; //DQ復位
delay(8); //稍做延時
DQ = 0; //單片機將DQ拉低
delay(80); //精確延時 大于 480us
DQ = 1; //拉高總線
delay(14);
x=DQ; //稍做延時后 如果x=0則初始化成功 x=1則初始化失敗
delay(20);
}
/******************************************************************************/
uchar ReadOneChar(void)//讀一個字節
{
uchar i=0;
uchar dat = 0;
for (i=8;i>0;i--)
{
DQ = 0; // 給脈沖信號
dat>>=1;
DQ = 1; // 給脈沖信號
if(DQ)
dat|=0x80;
delay(4);
}
return(dat);
}
/******************************************************************************/
void WriteOneChar(uchar dat)//寫一個字節
{
uchar i=0;
for (i=8; i>0; i--)
{
DQ = 0;
DQ = dat&0x01;
delay(5);
DQ = 1;
dat>>=1;
}
}
/******************************************************************************/
uint ReadTemperature(void)//讀取溫度
{
uchar a=0;
uchar b=0;
uint t=0;
float tt=0;
Init_DS18B20(); //第一次復位,執行溫度轉換
WriteOneChar(0xCC); // 跳過讀序號列號的操作
WriteOneChar(0x44); // 啟動溫度轉換
Init_DS18B20(); // 第二次復位,讀數據
WriteOneChar(0xCC); //跳過讀序號列號的操作
WriteOneChar(0xBE); //讀取溫度寄存器
a=ReadOneChar(); //讀低8位
b=ReadOneChar(); //讀高8位
t=b;
t<<=8;
t=t|a;
tt=t*0.0625;
t= tt*10+0.5; //放大10倍輸出并四舍五入
return(t);
}
main()
{
uint t;
while(1)
{
t= ReadTemperature();
if(t>999)
{
P1=dis_7[t/1000];
P3=0xfe;
delay(200);
P1=dis_7[(t%1000)/100];
P3=0xfd;
delay(200);
}
else
{
P1=dis_7[t/100];
P3=0xfd;
delay(200);
}
P1=(dis_7[(t%100)/10]&0x7f);
P3=0xfb;
delay(200);
P1=dis_7[t%10];
P3=0xf7;
if(t<1000)
{
SWH=0;
BEEP=1;
}
/* else if(t==999)
SWH=1;
else if(t==1000)
BEEP=0; */
else
{
SWH=1;
BEEP=0;
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -