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

📄 ds18b20.c

📁 单总线数字温度传感器DS18B20的c程序
💻 C
字号:
#include <REG51.H>

sbit DQ =P3^2;               //定义通信端口
/*--------------------------
延时函数
--------------------------*/
void delay11(unsigned int i)
{
 	while(i--);
}

/*--------------------------
初始化18B20
--------------------------*/
Init_DS18B20(void)
{
	 unsigned char temp_dq=0;
	 DQ = 1;                 //DQ复位
	 delay11(8);             //稍做延时
	 DQ = 0;                 //将DQ拉低
	 delay11(80);            //精确延时 大于 480us
	 DQ = 1;                 //拉高总线
	 delay11(14);
	 temp_dq=DQ;             //稍做延时后 如果x=0则初始化成功 x=1则初始化失败
	 delay11(20);
}

/*--------------------------
从18B20读一个字节
--------------------------*/
ReadOneChar(void)
{
	unsigned char i=0;
	unsigned char dat = 0;
	for (i=8;i>0;i--)
	 {
		  DQ = 0;           // 给脉冲信号
		  dat>>=1;
		  DQ = 1;           // 给脉冲信号
		  if(DQ)
		  dat|=0x80;
		  delay11(4);
	 }
 	return(dat);
}

/*--------------------------
向18B20写一个字节
--------------------------*/
WriteOneChar(unsigned char dat)
{
    unsigned char i=0;
    for (i=8; i>0; i--)
    {
        DQ = 0;
        DQ = dat&0x01;
        delay11(5);
        DQ = 1;
        dat>>=1;
    }
}

/*--------------------------
温度转换函数
--------------------------*/
void TempConversion()
{
    Init_DS18B20();
	WriteOneChar(0xCC);     // 跳过读序号列号的操作
	WriteOneChar(0x44);     // 启动温度转换   
}
/*--------------------------
读温度
--------------------------*/
ReadTemperature(void)
{
	unsigned char tl=0;
	unsigned char th=0;
	unsigned int   t=0;
	
	Init_DS18B20();
	WriteOneChar(0xCC);      //跳过读序号列号的操作
	WriteOneChar(0xBE);      //读取温度寄存器等(共可读9个寄存器) 前两个就是温度
	tl=ReadOneChar();
	th=ReadOneChar();
	t = th;
	t <<= 8;
	t = t|tl;
	t = t*0.625;               //有效位到小数点后1位
	return(t);
}

/*--------------------------
将整型数转换为字符串型
--------------------------*/
void IntToStr(unsigned int t, unsigned char *str) 
{

	str[0] = t/100+'0';       //百位,+'0'为数字转换成ASCII码
	str[1] = (t/10)%10+'0';   //十位
	str[3] = t%10+'0';        //个位
	str[2] = '.'; 
	str[4] = 'C';

} 

⌨️ 快捷键说明

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