/********************************************************************
程序名稱:DS18B20演示實驗
時鐘頻率:內(nèi)部RC 8M
芯片 :DS18B20
引腳 :**PA0 DATA**
**PD0--PD7接數(shù)碼管掃描端1--8**
**PC0--PC7接數(shù)碼管掃描端。.A--G**
********************************************************************/
#include
#include
#define DQ_H PORTA|=BIT(PA0);
#define DQ_L PORTA&=~BIT(PA0);
#define DQ_IN (PINA&0X01);
#define true 1
#define false 0
unsigned int m,i=0, temp,lsb,msb,num;
const unsigned char f[]=
{
0x7e,0x0c,0xb6,0x9e,0xcc,0xda,0xfa,0x0e,0xfe,0xde,0xee,0xf8,0x72,0xbc,0xf2,0xe2
};//碼段字型
voidDelay(unsigned int k)//延時
{
do
{
k--;
}
while(k>1);
}
void saomiao(void)//數(shù)碼管掃描
{
PORTC=f[m%10];
PORTD=0xfe;
Delay(900);
PORTC=f[m/10%10];
PORTD=0xfd;
Delay(900);
PORTC=f[m/100%10];
PORTD=0xfb;
Delay(900);
PORTC=0x01;
PORTD=0xf7;//小數(shù)點
Delay(900);
PORTC=f[m/1000%10];
PORTD=0xf7;
Delay(900);
PORTC=f[m/10000%10];
PORTD=0xef;
Delay(900);
PORTC=0x00;
PORTD=0xff;
Delay(900);
}
unsigned char ds1820_reset(void)//復(fù)位
{
unsigned char ack;
DDRA |=BIT(PA0);
DQ_L;
Delay(480);
DQ_H;
DDRA &= ~BIT(PA0);
Delay(45);
ack = DQ_IN;
Delay(420);
if(ack)
return true;
else
return false;
}
unsigned chards18b20_read_byte(void)//讀一字節(jié)
{
unsigned chari,num;
unsigned charvalue = 0;
for(i = 8; i > 0; i--)
{
value >>= 1;
DDRA |= BIT(PA0);
DQ_L;
Delay(16);
DQ_H;
DDRA &= ~BIT(PA0);
Delay(10);
num=DQ_IN;
if(num)
value|=0x80;
Delay(100);
DDRA|= BIT(PA0);
Delay(5);
}
return(value);
}
voidds18b20_write_byte(unsigned char value)//寫一字節(jié)
{
unsigned chari;
DDRA|= BIT(PA0);
for(i = 8; i > 0; i--)
{
if(value & 0x01)
{
DQ_L;
Delay(10);
DQ_H;
Delay(100);
}
else
{
DQ_L;
Delay(100);
DQ_H;
Delay(10);
}
value >>= 1;
}
}
unsigned intwendu()//讀取溫度值
{
unsigned char i;
unsigned int TEMP;
unsigned charTEMP_LSB,TEMP_MSB;
ds1820_reset();
ds18b20_write_byte(0xCC);//跳過ROM
ds18b20_write_byte(0x44);//啟動一次轉(zhuǎn)換
for(i = 0; i < 16; i++)
saomiao();//插入掃描
saomiao();
saomiao();
saomiao();
saomiao();
saomiao();
saomiao();
saomiao();
ds1820_reset();
ds18b20_write_byte(0xCC);//跳過ROM
ds18b20_write_byte(0xBE);//讀取溫度
TEMP_LSB = ds18b20_read_byte();
TEMP_MSB = ds18b20_read_byte();
TEMP=TEMP_MSB;
TEMP=TEMP<<8;
TEMP=TEMP|TEMP_LSB;
return(TEMP);
}
const unsigned char g[]=
{
0, 63, 130, 188, 250, 313,375,438,500, 563,625,688,750,813,875,938
};//小數(shù)點后數(shù)據(jù)轉(zhuǎn)換(減少運算負擔(dān))
void main(void)//主程序
{
DDRD=0xff;
DDRC=0xff;
PORTD=0;
PORTC=0;
while(1)
{
num=wendu();
temp=(num>>8)&0xf0;
if(temp==0xf0)
{
num=(~num)+1;
i=num&0x0f;
lsb=g[i];
msb=(num>>4)&0xff;
}
else
{
i=num&0x0f;
lsb=g[i];
msb=(num>>4)&0xff;
}
m=msb*1000+lsb;
for (i=0;i<6;i++)
{
saomiao();
}
}
}