M8,ICCAVR下的溫度傳感器18B20程序
本程序?yàn)椴捎胢ega8 和18b20的溫度采集程序
選用mega8內(nèi)部8M RC震蕩,18b20 數(shù)據(jù)線接pd6,數(shù)據(jù)線和vcc間接一4.7k上拉電阻
感謝dfgeoff 嗜血蝸牛提供的資料*/
#include
#include
#define uchar unsigned char
#define uint unsigned int
void init_1820();
write_1820(uchar x);
uchar read_1820();
void send_byte(uchar x);
void delay(uint x);
void disp_led(uchar buffer,uchar control);
uchar disp_table[16] = {
0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,
0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71};
uchar dp;
long count;
void main(void) //主函數(shù)
{
disp_led(0,0);
delay(2000);
OSCCAL=0X9d;//系統(tǒng)時(shí)鐘校準(zhǔn),不同的芯片和不同的頻率,
DDRC=0xff;
DDRD=0XFF;
PORTD=0XFF;
WDR(); //看門狗計(jì)數(shù)清零
WDTCR=0x0F;
PORTC=0xff;
while(1)
{
uchar i,temh,teml;
init_1820(); //復(fù)位18b20
write_1820(0xcc); // 發(fā)出轉(zhuǎn)換命令
write_1820(0x44);
delay(400);
init_1820();
WDR();
write_1820(0xcc); //發(fā)出讀命令
write_1820(0xbe);
teml=read_1820(); //讀數(shù)據(jù)
temh=read_1820();
//for(i=0;i<7;i++) //測(cè)試用
//{
//send_byte(0x40);
//send_byte(disp_table[0&0x0f]);
//}
//send_byte(disp_table[temh>>4]);
//send_byte(disp_table[temh&0x0f]);
//send_byte(disp_table[teml>>4]);
//send_byte(disp_table[teml&0x0f]);
count=(temh*256+teml)*6.25; //計(jì)算具體溫度
WDR();
disp_led(0,1); //顯示溫度
for(i=0;i<100;i++) //每次轉(zhuǎn)換需要延時(shí)200ms以上
delay(1000);
}
}
void delay(uint x) //1.5us左右
{
while(x)
{
x--;
}
}
void init_1820()
{
PORTD|=(1<<6);
PORTD&=~(1<<6);
delay(3000); //480us以上
PORTD|=(1<<6);
DDRD&=~(1<<6);
delay(40); //15~60us
while(PIND&(1<<6))
{
// disp_led(3,0);
// for(;;)
//{}
}
DDRD|=(1<<6);
PORTD|=(1<<6);
delay(150); //60~240us
}
write_1820(uchar x)
{
uchar m;
for(m=0;m<8;m++)
{
PORTD&=~(1<<6);
if(x&(1<
else
PORTD&=~(1<<6);
delay(40); //15~60us
PORTD|=(1<<6);
}
PORTD|=(1<<6);
}
uchar read_1820()
{
uchar temp,k,n;
temp=0;
for(n=0;n<8;n++)
{
PORTD&=~(1<<6);
//delay(2);
PORTD|=(1<<6);
//delay(3);
DDRD&=~(1<<6);
k=(PIND&(1<<6)); //讀數(shù)據(jù),從低位開始
if(k)
temp|=(1<
temp&=~(1<
DDRD|=(1<<6);
}
return (temp);
}
void send_byte(uchar x) //以下為顯示程序
{
uchar i;
for(i=0;i<8;i++)
{
PORTC&=~(1<<5); // PC5為底 為164提供時(shí)鐘信號(hào)
if((x&(1<<(7-i)))||((dp==1)&&(i==0))) //判斷每位數(shù)據(jù)的電平,及小數(shù)點(diǎn)判斷
PORTC|=(1<<4); //若為高著PC4輸出高電平
else
PORTC&=~(1<<4); //若為低著輸出低電平
PORTC|=(1<<5); //PC5 提供始終信號(hào)
}
//PORTC|=((1<<0)|(1<<1)|(1<<2));
}
//顯示程序 CONTROL為控制顯示 BUFFER為顯示數(shù)據(jù)
void disp_led(uchar buffer,uchar control)
{
uchar i,temp[6];
uint tempcount;
dp=0;
switch(control)
{
case 0: //CONTROL為零全部數(shù)碼管顯示buffer
{
for(i=0;i<11;i++)
send_byte(disp_table[buffer%10]);//顯示數(shù)字
break;
}
case 1: //control為1,顯示count中的數(shù)據(jù)為6位
{
tempcount=count;
for(i=0;i<6;i++) //取出每位中的數(shù)據(jù)
{
temp[i]=tempcount%10;
tempcount/=10;
}
send_byte(disp_table[buffer/10]); //最開始顯示buffer數(shù)據(jù)
send_byte(disp_table[buffer%10]);
send_byte(0x00);
send_byte(0x00);
send_byte(0x00);
for(i=0;i<6;i++)
{
if(i==3)
dp=1; //小數(shù)點(diǎn)控制位
send_byte(disp_table[temp[5-i]]);
dp=0;
}
break;
}
}
PORTC|=(1<<4);
}