×
单片机 > 单片机程序设计 > 详情

AVR单片机测温基于DS18B20

发布时间:2020-05-28 发布时间:
|

#include

#include

#include

#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);


}

}


}


关键字:AVR  单片机测温  DS18B20 

『本文转载自网络,版权归原作者所有,如有侵权请联系删除』

热门文章 更多
如何为单片机选择合适的负载电容