?? 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 + -