标题: ds18b20 温度模块串口显示简单代码 [打印本页]

作者: chenyinhu    时间: 2019-9-24 23:17
标题: ds18b20 温度模块串口显示简单代码
今天晚上没事干编了一个极简的一个小程序,虽然简单但是还是很稳定的,连接也很简单,用最小系统板p0.0口接上ds18b20模块就可以了

#include <reg51.h>
#include <intrins.h>
#include <stdio.h>
#include "DS18B20.h"
#define OSC 11059200            //晶振频率
#define BAUDRATE 9600    //波特率

void main(void)
{

       unsigned int i;
       unsigned char tmph,tmpl;
       Temp t;
       unsigned char strTemp[8];    //显示到屏幕的温度数据
                           //开背光
       TMOD = 0x21;                  //选择方式2作为波特率发生
       SCON = 0x50;                   //串口方式1,允许中断
       PCON |= 0x80;                  //SMOD=1
       TL1 = 256 -(OSC/12/16/BAUDRATE);
       TH1 = 256 -(OSC/12/16/BAUDRATE);
       TR1 = 1;                                  //启动定时器
       TI = 1;                                   //TI有效
//检测DS18B20温度传感器是否存在并复位传感器
       if(DSReset())
           printf("\r\Temp sensor ResetOK!");
       else  printf("\r\Temp Sensor Notready!");
          
    while(1){
       
          DSReset();                             //复位传感器
          Delay(1);
          DSWriteByte(SkipROM);                  //跳读 省时
          DSWriteByte(StartConvert);             //温度转换
          for(i=0;i<40000;i++);
          DSReset();
          Delay(1);
          DSWriteByte(SkipROM);
          DSWriteByte(ReadMemory);   //读RAM程序
          tmpl = DSReadByte();
          tmph = DSReadByte();
          printf("\r\nTemperature code HI=%02bX,LO=%02bX ",tmph,tmpl);
          DSReadTemp(&t);
//准备输出到显示屏的数据
        strTemp[0]=t.z/10+0x30;     //十位
        strTemp[1]=t.z%10+0x30;     //个位
        strTemp[2]='.';             //小数点
        strTemp[3]=t.x/1000+0x30;   //十分位
        strTemp[4]=(t.x/100)%10+0x30; //百分位
                strTemp[5]=(t.x/10)%10+0x30;//千分位
                strTemp[6]=t.x%10+0x30;            //万分位
        strTemp[7]='C';
              if(t.z>=30)
              printf("\nWarning!!!Temperature= %d.%04d ",t.z,t.x) ;  //大于30度温度警告
              else
        printf("\r\nTemperature = %d.%04d",t.z,t.x);

}
}

U%$`HK1Y@B98$CCYHITWL7K.png (80.25 KB, 下载次数: 53)

串口助手显示选9600波特率

串口助手显示选9600波特率

IMG_20190924_230416.jpg (2.42 MB, 下载次数: 43)

实物连接,其实就一根线

实物连接,其实就一根线

温度串口显示.zip

47 KB, 下载次数: 64, 下载积分: 黑币 -5


作者: zskjgw    时间: 2019-11-14 08:41
支持!




欢迎光临 (http://www.51hei.com/bbs/) Powered by Discuz! X3.1