栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

【蓝桥之路——无bug代码】DS18B20温度读取代码解析

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【蓝桥之路——无bug代码】DS18B20温度读取代码解析

通过DS18B20测量外界温度并显示在数码管上,温度值需精确到小数点后2位

main.c

#include"STC15F2K60S2.h"
#include"onewire.h"
#include"intrins.h"

typedef unsigned char uchar;
typedef unsigned int uint;

uchar dsp_code[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};
uchar dsp_Temp[8]={0xff,0xff,0xff,0xff};

uint temp;
uchar count_temp;

void Timer_Init()
{
	AUXR|= 0x80;
	TMOD&= 0xf0;
	TL0=0xcd;
	TH0=0xd4;
	TR0=1;
	ET0=1;
	EA=1;
}

void serviceTimer() interrupt 1
{
	static uchar dsp_com=0;

	P0=0;P2=0xc0;P2=0;

	P0=dsp_Temp[dsp_com];P2=0xe0;P2=0;

	P0=1<759)
		{
			count_temp=0;
			temp=read_temp()*100+0.5;
		}
	dsp_Temp[4]=dsp_code[temp/1000];
	dsp_Temp[5]=dsp_code[temp/100%10]&0x7f;
	dsp_Temp[6]=dsp_code[temp/10%10];
	dsp_Temp[7]=dsp_code[temp%10];
	}
}

onewire.c

#include "reg52.h"
#include"onewire.h"
#include"intrins.h"

sbit DQ = P1^4;  //单总线接口

//单总线延时函数
void Delay_oneWire(unsigned int t);  //STC89C52RC

//通过单总线向DS18B20写一个字节
void Write_DS18B20(unsigned char dat)
{
	unsigned char i;
	for(i=0;i<8;i++)
	{
		DQ = 0;
		DQ = dat&0x01;
		Delay_oneWire(5);
		DQ = 1;
		dat >>= 1;
	}
	Delay_oneWire(5);
}

//从DS18B20读取一个字节
unsigned char Read_DS18B20(void)
{
	unsigned char i;
	unsigned char dat;
  
	for(i=0;i<8;i++)
	{
		DQ = 0;
		dat >>= 1;
		DQ = 1;
		if(DQ)
		{
			dat |= 0x80;
		}	    
		Delay_oneWire(5);
	}
	return dat;
}

//DS18B20设备初始化
bit init_ds18b20(void)
{
  	bit initflag = 0;
  	
  	DQ = 1;
  	Delay_oneWire(12);
  	DQ = 0;
  	Delay_oneWire(80);
  	DQ = 1;
  	Delay_oneWire(10); 
    initflag = DQ;     
  	Delay_oneWire(5);
  
  	return initflag;
}

void Delay_onewire(unsigned int t)
{
	t*=11;
	while(t--);
}

float read_temp()
{
	float temp;
	unsigned char low,high;

	init_ds18b20();
	Write_DS18B20(0xcc);
	Write_DS18B20(0x44);
	Delay_oneWire(200);

	init_ds18b20();
	Write_DS18B20(0xcc);
	Write_DS18B20(0xbe);
	low=Read_DS18B20();
	high=Read_DS18B20();
	temp=(high<<8|low)*0.0625;

	return temp;
}

 onewire.h

#ifndef __ONEWIRE_H
#define __ONEWIRE_H

float read_temp();
bit init_ds18b20(void);
unsigned char Read_DS18B20(void);
void Delay_oneWire(unsigned int t);
void Write_DS18B20(unsigned char dat);
unsigned char rd_temperature(void);  //; ;

#endif

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/738807.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号