18B20的驱动代码

1、18B20.H代码

#ifndef __DS18B20_H__
#define __DS18B20_H__

#include "REG51.H"
#include "string.h"
#include "intrins.H"
#include "stdio.h"
#include"delay.h"

#define uchar unsigned char
#define uint  unsigned int


sbit DS = P0^3;

extern unsigned int TEMP;



void delay_us(uchar us);
//void Delay1000ms();		//@11.0592MHz
void DS18B20_init();
void DSWriteByte(uchar dat);    //总线每次只能写一位进去
uchar DSReadByte();
void DS18B20_Read();

#endif

2、18B20.C代码

#include "ds18b20.h" 

unsigned int TEMP=0;

void delay_us(uchar us)
{
  while(us--);
}

void DS18B20_init()
{				
	DS = 1;
	_nop_();
	DS = 0;
	delay_us(80);
    DS = 1;
	delay_us(7);
	while(0 == DS);
	DS = 1;
}

//写一个字节

void DSWriteByte(uchar dat)    //总线每次只能写一位进去
{
  uchar i;
  for(i = 0;i<8;i++)
  {
    DS = 0;   //下拉总线
    _nop_();    //产生一点时序
    DS = dat & 0x01;    //0x01  00000001
    delay_us(10);   //76.95us
    DS = 1;   //上拉总线
    _nop_();
    dat >>= 1;    //dat右移一位
  }
}
//读一个字节
uchar DSReadByte()
{
  unsigned char i,j,dat;
	for(i=0;i<8;i++)
	{
		DS = 0;
		_nop_();
		DS = 1;
		j = DS;
		_nop_();
		_nop_();;
		dat = (dat>>1)|(j<<7);
		delay_us(5);
		DS = 1;
	}
	return dat;
}

void DS18B20_Read()
{
	uchar L,M,bai,shi,ge;
	uint i;
	
	DS18B20_init();   //初始化
	delay_us(10);
    DSWriteByte(0xcc);    //发送忽略ROM指令
    DSWriteByte(0x44);    //发送完指令后,DS18B20开始转换并且存储到高速寄存器
    DS18B20_init();
	delay_us(10);
    DSWriteByte(0xcc);    //发送忽略ROM指令
    DSWriteByte(0xbe);    //读取DS18B20暂存器指令
    L = DSReadByte();   //读取LS BYTE
    M = DSReadByte();   //读取MS BYTE
    i = M;
    i <<=8;
    i = i|L;		//效果为	假设M为00000111 左移八位变为 0000011100000000(<<自动补全0)然后或上L,相当于M+L 
    i = i*0.0625*100+0.5;   //+0.5 为了四舍五入。因为if为int型,自动抛掉小数点后面
	bai = (i / 10000);
	shi = (i % 10000/1000);		
	ge  = (i % 1000/100);
		
	TEMP=shi*10+ge;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值