⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ds18b20.c

📁 AVR Devolpment Board
💻 C
字号:
#include "avr/io.h"
#include "util/delay.h"

#define CLR_DQ  (PORTA&=~(1<<PA1))
#define SET_DQ  (PORTA|= (1<<PA1))
#define DQ      ((PINA>>PA1)&0x01)

#define DQ_IN   (DDRA &=~(1<<PA1))
#define DQ_OUT  (DDRA |= (1<<PA1))

unsigned char tflag=0;

void delay_us(unsigned int us)
{
	while(us--)
		_delay_us(1);
}

/* Reset the device */
void ds1820rst()
{
	DQ_OUT;
	CLR_DQ;
	delay_us(500);  /* Delay must more the 480us */
	SET_DQ;
	delay_us(500);  /* Delay a short time */	 
}  

/* Read data from the device */
unsigned char ds1820rd()
{
	unsigned char i=0;
	unsigned char dat = 0;
	for (i=8;i>0;i--)
	{
		dat>>=1;

		DQ_OUT;
		CLR_DQ;
		
		SET_DQ; 	/* Set dq as input pin and enable the pull up resistance */
		DQ_IN;
		
		if(DQ)
			dat|=0x80;

		delay_us(50);
	}
	return(dat);
}

/* Write data to the device */
void ds1820wr(unsigned char wdata)
{
	unsigned char i=0;
	for (i=8; i>0; i--)
	{
		DQ_OUT;
		CLR_DQ;
		
		if(wdata&0x01)
			SET_DQ;
		else
			CLR_DQ;

		delay_us(50);
		SET_DQ;
		wdata>>=1;
	}
}
 
/* Read data and change to tempreture */
float read_temp()
{
	unsigned char a,b;
	float tvalue;
	ds1820rst();    
	ds1820wr(0xcc);    /* Skip read the device ID */
	ds1820wr(0x44);    /* Start convert tempreture */
	ds1820rst();    
	ds1820wr(0xcc);    /* Skip read the device ID */
	ds1820wr(0xbe);    /* Read data */
	a=ds1820rd();
	b=ds1820rd();	
	tvalue=((b<<8)|a)*0.0625;/* Change to tempreture */
	return(tvalue);
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -