#include<iom16v.h>
#include<macros.h>
#include<delay.h>
#define uint unsigned int
#define uchar unsigned char
#define dula_set PORTA |=BIT(3) //數碼管段選
#define dula_clr PORTA &=~BIT(3)
#define wale_set PORTA |=BIT(4)//數碼管位選
#define wale_clr PORTA &=~BIT(4)
#define DQ_IN DDRA&=~BIT(5)
#define DQ_OUT DDRA|=BIT(5)
#define DQ_SET PORTA|=BIT(5)
#define DQ_CLR PORTA&=~BIT(5)
#define DQ_R PINA&BIT(5)//讀第2位
uchar smg_du[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x40};//數碼管段碼
uchar smg_wei[]={0xfe,0xfd,0xfb,0xf7,0xef,0xdf,0xbf,0x7f};// 數碼管位碼
uchar table[8]={0,0,0,0,0,0,0,0};//存放轉換后的數
void delay()
{
uint a;
for(a=0;a<300;a++);
}
/////////
void display(uchar *p)//顯示函數
{
uchar i;
for( i=0; i<8; i++) //實現8位動態掃描循環
{
dula_set;
PORTB=smg_du[*p]; //將字模送到P0口顯示
p++;
if(i==1)//為1是在第2個數碼管顯示小數點
{
PORTB|=BIT(7);
}
else
{
PORTB&=~BIT(7);
}
dula_clr;
wale_set;
PORTB=smg_wei[i];
wale_clr;
delay();
}
}
//////
uchar ds18b20_reset(void)//復位
{
uchar i;
DQ_OUT;
DQ_CLR;
delay_n100us(5);
DQ_SET;
delay_100us();
DQ_IN;
i=DQ_R;
delay_n100us(5);
return i;
}
//////
void ds18b20_write_byte(uchar value)//寫一個字節
{
uchar i;
for(i=0;i<8;i++)
{
DQ_OUT;
DQ_CLR;
delay_10us();
if(value&0x01)//判斷最低位是否為1
{
DQ_SET;
}
delay_n100us(1);
DQ_SET;
value=value>>1;
}
}
///////
uchar ds18b20_read_byte(void)//讀一個字節
{
uchar i;
uchar value;
for(i=0;i<8;i++)
{
value=value>>1;
DQ_OUT;
DQ_CLR;
delay_10us();
DQ_SET;
DQ_IN;
if(DQ_R)
{
value|=0x80;
}
delay_50us();
}
return value;
}
//////
void data_pro(uint temp)//數據處理
{
table[0]=temp/1000;
table[1]=(temp%1000)/100;
table[2]=(temp%100)/10;
table[3]=temp%10;
}
//////
void main(void)
{
uchar i,j,k;
uint temp;
DDRB=0xff;
PORTB=0xff;
DDRA|=BIT(3);
PORTA|=BIT(3);
DDRA|=BIT(4);
PORTA|=BIT(4);
while(1)
{
ds18b20_reset();
ds18b20_write_byte(0xcc);//跳過ROM
ds18b20_write_byte(0x44);//啟動轉換
delay_n100us(20);
ds18b20_reset();
ds18b20_write_byte(0xcc);
ds18b20_write_byte(0xbe);//讀取溫度
i=ds18b20_read_byte();//lsb
j=ds18b20_read_byte();//msb
temp=j*256+i;
temp=temp*6.25;
data_pro(temp);
for(k=0;k<20;k++)
{
display(table);
}
}
}
|