您的位置:首页 > 编程语言 > C语言/C++

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

2012-09-01 19:37 316 查看
代码是在12M的晶振的晶振下调试出来的,希望可以给大家带来参考价值

#include <reg51.h> //51芯片管脚定义头文件

#include <intrins.h> //内部包含延时函数 _nop_();

#include<stdio.h>

#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|(temp1%1000/100);

delay(10);

P1 = 0x20|(temp1%1000%100/10);

delay(10);

P1 = 0x10|(temp1%1000%100%10);

}

main()

{while(1)

{

tempchange();

Display1(); //显示温度

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  语言 delay c float