给跪了:问个关于DS18B20的问题,显示85.0度,不变
/* 环境:STC89C52 DS18B20接P1^2 数码管(四位一体共阴极数码管)P3口位选:0x77,0x6f,0x5f,0x3f 段选:P2。 */ #include "reg52.h" #define uchar unsigned char #define uint unsigned int uint temp; float f_temp; sbit ds=P1^2; //温度传感器信号线 uchar code table[]= //不带小数点 { 0xfc,0x60,0xD9,0xf1,0x65,0xb5,0xbd,0xe0,0xfd,0xf5 }; unsigned char code table1[]= //带小数点 { 0xfe,0x62,0xdb,0xf3,0x67,0xb7,0xbf,0xe2,0xff,0xf7 }; uchar code table2[]= //位选 { 0x77,0x6f,0x5f,0x3f }; void delay(uint z)//延时函数 { uint x,y; for(x=z;x>0;x--) for(y=110;y>0;y--); } void dsreset(void) //18B20复位,初始化函数 { uint i; ds=0; i=103; while(i>0)i--; ds=1; i=4; while(i>0)i--; } bit tempreadbit(void) //读1位函数 { uint i; bit dat; ds=0;i++; //i++ 起延时作用 ds=1;i++;i++; dat=ds; i=8;while(i>0)i--; return (dat); } uchar tempread(void) //读1个字节 { uchar i,j,dat; dat=0; for(i=1;i<=8;i++) { j=tempreadbit(); dat=(j<<7)|(dat>>1); //读出的数据最低位在最前面,这样刚好一个字节在DAT里 } return(dat); } void tempwritebyte(uchar dat) //向18B20写一个字节数据 { uint i; uchar j; bit testb; for(j=1;j<=8;j++) { testb=dat&0x01; dat=dat>>1; if(testb) //写 1 { ds=0; i++;i++; ds=1; i=8;while(i>0)i--; } else { ds=0; //写 0 i=8;while(i>0)i--; ds=1; i++;i++; } } } void tempchange(void) //DS18B20 开始获取温度并转换 { dsreset(); delay(1); tempwritebyte(0xcc); // 写跳过读ROM指令 tempwritebyte(0x44); // 写温度转换指令 } uint get_temp() //读取寄存器中存储的温度数据 { uchar a,b; dsreset(); delay(1); tempwritebyte(0xcc); tempwritebyte(0xbe); a=tempread(); //读低8位 b=tempread(); //读高8位 temp=b; temp<<=8; //两个字节组合为1个字 temp=temp|a; f_temp=temp*0.0625; //温度在寄存器中为12位 分辨率位0.0625° temp=f_temp*10+0.5; //乘以10表示小数点后面只取1位,加0.5是四舍五入 f_temp=f_temp+0.05; return temp; //temp是整型 } ////////////////////显示程序////////////////////////// void display() { uchar i; uchar ge,shi,bai; i=get_temp(); //temp=256; bai=temp/100; shi=temp%100/10; ge=temp%100%10; P3=0x77; P2=table[bai]; delay(1); P3=0x6f; P2=table1[shi]; delay(1); P3=0x5f; P2=table[ge]; delay(1); P3=0x3f; P2=0x9c; } void main() { P3=0; P2=0; while(1) { tempchange(); display(); } }
回复
有奖活动 | |
---|---|
【有奖活动——B站互动赢积分】活动开启啦! | |
【有奖活动】分享技术经验,兑换京东卡 | |
话不多说,快进群! | |
请大声喊出:我要开发板! | |
【有奖活动】EEPW网站征稿正在进行时,欢迎踊跃投稿啦 | |
奖!发布技术笔记,技术评测贴换取您心仪的礼品 | |
打赏了!打赏了!打赏了! |