锐单电子商城 , 一站式电子元器件采购平台!
  • 电话:400-990-0325

基于单片机的温度传感器18b20的C语言程序

时间:2022-08-29 17:30:00 传感器pr9268201t44传感器

代码是在12M晶振晶振下调试,希望能给大家带来参考价值

#include //51芯片管脚定义头文件

#include ///内部包含延迟函数 _nop_();

#include

#define uchar unsigned char

#define uint unsigned int

uchar Flag=0;///定义全局标志位

uchar Feng=0;

sbit ds= P3^1; //接18B20

void delay(uint t)

{

uint k;

while(t--)

{

for(k=0; k<12; k )

{ }

}

}

void dsreset(void)///初始化函数

{

uint i;

ds=0;

i=97;

while(i>0)

i--;

ds=1;

i=4;

while(i>0)

i--;

}

bit tempreadbit(void) ///读一个字节

{

uint i;

bit dat;

ds=0;

i ;

ds=1;

i ; //i 起延时作用

i ;

dat=ds;

i=8;

while(i>0)

i--;

return(dat);

}

uchar tempread(void)///阅读数据

{

uchar i=8,dat=0;

bit j;

for(i=1;i<=8;i )

{

dat=dat>>1;

j=tempreadbit();

if(j==1)

dat=dat|(0x80);

}

return(dat);

}

void tempwritebyte(uchar dat)///写字节

{

uint i;

uchar j;

bit testb;

for(j=1;j<=8;j )

{

testb=dat&(0x01);

dat=dat>>1;

if(testb)

{

ds=0;

i ;

i ;

ds=1;

i=8;

while(i>0)

i--;

}

else

{

ds=0;

i=8;

while(i>0)

i--;

ds=1;

i ;

i ;

}

}

}

void tempchange(void)

{

dsreset();

delay(1);

tempwritebyte(0xcc); //写跳读rom

tempwritebyte(0x44); //写温度转换

}

float get_temp()

{

uchar a;

uint b;

float Read_Value;

dsreset();

//tempwritebyte(0xcc); //写跳读rom

//tempwritebyte(0x44); //写温度转换

delay(10);

//dsreset();

tempwritebyte(0xcc);//写跳过读ROM

tempwritebyte(0xbe);///读暂存器

a = tempread();

b = tempread();

b = (b << 8) a;

Read_Value = b *0.0625;

//delay(1000);

return(Read_Value);

}

void Display1() //显示温度

{

int temp,temp1;

temp=get_temp();

temp1 = temp*100;

P1 = 0x80|(temp1/1000);

delay(10);

P1 = 0x40|(temp100/100);

delay(10);

P1 = 0x20|(temp1000/10);

delay(10);

P1 = 0x10|(temp1000);

}

main()

{while(1)

{

tempchange();

Display1(); //显示温度

}

}

锐单商城拥有海量元器件数据手册IC替代型号,打造电子元器件IC百科大全!

相关文章