DS18B20的C语言驱动程序

电子说

1.2w人已加入

描述

  DS18B20驱动程序(C语言)

  //#include“reg51.h”

  sbit DQ =P1^4; //定义通信端口

  //延时函数

  /*

  void delay(unsigned int i)

  {

  while(i--);

  }

  */

  //初始化函数

  Init_DS18B20(void)

  {

  unsigned char x=0;

  DQ = 1; //DQ复位

  delay(8); //稍做延时

  DQ = 0; //单片机将DQ拉低

  delay(80); //精确延时 大于 480us

  DQ = 1; //拉高总线

  delay(14);

  x=DQ; //稍做延时后 如果x=0则初始化成功 x=1则初始化失败

  delay(20);

  }

  //读一个字节

  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;

  delay(4);

  }

  return(dat);

  }

  //写一个字节

  WriteOneChar(unsigned char dat)

  {

  unsigned char i=0;

  for (i=8; i》0; i--)

  {

  DQ = 0;

  DQ = dat&0x01;

  delay(5);

  DQ = 1;

  dat》》=1;

  }

  //delay(4);

  }

  //DS18B20程序读取温度

  ReadTemperature(void)

  {

  unsigned char a=0;

  unsigned char b=0;

  unsigned int t=0;

  float tt=0;

  Init_DS18B20();

  WriteOneChar(0xCC); // 跳过读序号列号的操作

  WriteOneChar(0x44); // 启动温度转换

  Init_DS18B20();

  WriteOneChar(0xCC); //跳过读序号列号的操作

  WriteOneChar(0xBE); //读取温度寄存器等(共可读9个寄存器) 前两个就是温度

  a=ReadOneChar();

  b=ReadOneChar();

  t=b;

  t《《=8;

  t=t|a;

  tt=t*0.0625;

  //t= tt*10+0.5; //放大10倍输出并四舍五入---此行没用

  return(t);

  }

  //DS18B20主程序

  main()

  {

  unsigned char i=0;

  while(1)

  {

  i=ReadTemperature();//读温度

  }

  }

  ds18b20c语言程序完毕

打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分