单片机小白
DS18B20温度传感器的数据经过处理显示在数码管上
运行效果:
代码:
#include#include typedef unsigned char u8; typedef unsigned int u16; typedef signed int s16; sbit IO_18B20=P3^7; sbit add_1=P2^2; sbit add_2=P2^3; sbit add_3=P2^4; u8 DQ; u8 c[8]; u8 code a[10]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};//0-9 void Delay_ms(unsigned char ms)//定时器延时函数 { unsigned char T=0; TMOD=0x01; TH0=0xfb; TL0=0x80; TR0=1; while(T if(TF0==1) { TF0=0; TH0=0xfb2 ; TL0=0x80; T++; } } }//1.25*ms void Delay(u16 i)//延时 { while(i--); } void init_18B20()//DS18B20初始化 { IO_18B20=0; Delay(100); IO_18B20=1; Delay(5); DQ=IO_18B20; Delay(80); } void write_cmd(u8 cmd)//DS18B20写时序 { u8 i; for(i=0;i<8;i++) { IO_18B20=0; _nop_(); IO_18B20=cmd&0x01; Delay(6); IO_18B20=1; cmd>>=1; } } u8 read_cmd()//DS18B20读时序 { u8 j,by,byte; for(j=0;j<8;j++) { IO_18B20=0; _nop_(); IO_18B20=1; _nop_(); _nop_(); by=IO_18B20; byte=(byte>>1)|(by<<7); Delay(4); } return byte; } void change_temper()//温度转换 { init_18B20(); if(DQ==0) { write_cmd(0xcc);//跳过ROM write_cmd(0x44);//温度转换后存储在暂存寄存器的2个字节长度的温度寄存器中 } } void read_temper()//读温度 { init_18B20(); if(DQ==0) { write_cmd(0xcc);//跳过ROM write_cmd(0xbe);//读取暂存寄存器 } } s16 DS18B20temp_data()//采集DS18B20中cache温度数据 { s16 temp; u8 temph,templ; change_temper(); read_temper(); templ=read_cmd(); temph=read_cmd(); temp=temph; temp<<=8; temp|=templ; return temp; } void datapros(s16 temp)//将采集的数据按照规定的分辨率转化为数字 { float tp; if(temp<0) { c[0]=0x40; temp=~temp; temp+=1; tp=temp; temp=tp*0.0625*100+0.5; } else { tp=temp; temp=tp*0.0625*100+0.5; //0.0625为分辨率 100:保留两位小数 0.5:精度 } c[1] = a[temp/1000%10];//显示温度十位 c[2] = a[temp/100%10]+0x80;//显示温度个位 c[3] = a[temp/10%10];//显示一位小数 } void shuaxin()//刷新数码管 { add_1=0; add_2=0; add_3=0; P0=0x39; //数码管显示 C Delay_ms(1); P0=0x00; add_1=1; add_2=0; add_3=0; P0=c[3]; Delay_ms(1); P0=0x00; add_1=0; add_2=1; add_3=0; P0=c[2]; Delay_ms(1); P0=0x00; add_1=1; add_2=1; add_3=0; P0=c[1]; Delay_ms(1); P0=0x00; add_1=0; add_2=0; add_3=1; P0=c[0]; Delay_ms(1); P0=0x00; } void main()//主函数 ---显示 { while(1) { datapros(DS18B20temp_data()); shuaxin(); } }



