基于STC15W204S的18B20温度检测程序

2025-11-18 05:09:54

基于STC15W204S的18B20温度检测程序,关于STC15W204S单片机程序资源较少,因此特意拿出分享!

工具/原料

STC15W204S

18b20

方法/步骤

#include<STC15F104E.H> 

#define ulong unsigned long

 #define uchar unsigned char     

#define uint unsigned int 

sbit temp=P5^5;       //18B20 

void delay(unsigned int time){   

 unsigned int n;  

  n=0;    

while(n<time) {n++;}    

return; 

/*********************/ 

void Delay_DS18B20(ulong num){    

while(num--);

 }/*****初始化DS18B20*****/

 void Init_DS18B20(void){   

unsigned char x=0;   temp = 1;          //temp复位   

Delay_DS18B20(2);   //稍做延时   

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

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

 temp = 1;          //拉高总线   

Delay_DS18B20(14);  

 x = temp;            //稍做延时后,如果x=0则初始化成功,x=1则初始化失败   Delay_DS18B20(20); 

}/*****读一个字节*****/ 

unsigned char ReadOneChar(void){   

unsigned char i=0;   

unsigned char dat = 0;  

 for (i=8;i>0;i--)   {   

temp = 0;     // 给脉冲信号   

dat>>=1;   

temp = 1;     // 给脉冲信号  

 if(temp)   dat|=0x80;  

 Delay_DS18B20(8);  

 }   

return(dat);

 }/*****写一个字节*****/

 void WriteOneChar(unsigned char dat){   

unsigned char i=0;  

 for (i=8; i>0; i--)   {  

 temp = 0;  

 temp = dat&0x01;  

 Delay_DS18B20(10);  

 temp = 1;  

 dat>>=1;  

 }

 }/*****读取温度*****/

 unsigned int ReadTemperature(void){   

unsigned char a=0;  

 unsigned char b=0;   

unsigned int t=0;   

float tt=0;   

Init_DS18B20();   

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

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

Delay_DS18B20(20);  

 Init_DS18B20();   

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

WriteOneChar(0xBE); //读取温度寄存器   

a=ReadOneChar();      //读低8位   

b=ReadOneChar();    //读高8位  

 t=b;   t<<=8;  

 t=t|a;   tt=t*0.0625;  

 t= tt*10+0.5;      //放大10倍输出并四舍五入  

 return(t);}

18b20读取口设置为P5.5(可以修改)。以上是温度读取函数,读取为t(数值型)然后加入主函数

void main(){   

 while(1)    {         

    display=t;

  }

 }

至于显示函数display(),这不必多说。基本上都会,加入就可以显示t的值,记得加入主函数里面,才会运行。

注意事项

注意18b20的连接方式

注意STC15W204S下载时候,配置晶振频率为24Mhz。

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢