本项目为基于51单片机的温度传感程序设计,能够实时采集环境温度数据,并通过数码管或LCD显示。适用于教学、实验及小型测温设备开发。
以下是经过处理的代码段:
```c
#include
#define uchar unsigned char
#define uint unsigned int
sbit led = P2^5;
sbit wei = P2^7;
sbit duan = P2^6;
sbit DQ = P2^2;
uchar mazhi_duan[] = {0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07,
0x7f, 0x6f, 0x77, 0x7c, 0x39, 0x5e, 0x79, 0x71,
0x84}; // 数码管段选表
uchar mazhi_wei[] = {0xfe, 0xfd, 0xfb, 0xf7, 0xef,
0xdf, 0xff}; // 共阴数码管位选表
void delayl(uint n) {
uint i,j;
for(i=n; i>0; i--)
for(j=114; j>0; j--);
}
void delays(uchar i){
while(i--);
}
bit init_DS18B20() { // DS8B20初始化
bit x;
DQ = 1;
delays(8);
DQ = 0;
delays(75);
DQ = 1;
delays(15);
x=DQ;
delays(5);
return x;
}
void write_data(uchar dat){
uchar i,temp;
temp=dat;
for(i=0;i<8;i++) {
DQ = 0;
delays(1);
if(temp&0x01)
DQ = 1;
else
DQ = 0;
delays(4);
temp>>=1;
}
}
uchar read_data(){
uchar i,dat;
for(i=0;i<8;i++) {
dat>>=1;
if(DQ)
dat|=0x80;
DQ = 1; //配置为输入
delays(4);
}
return dat;
}
uint readtemp(){
uchar temph,templ;
uint temp;
float wendu;
init_DS18B20();
write_data(0xcc);//跳过ROM
write_data(0x44);//启动温度转换
delayl(100);
init_DS18B20();
write_data(0xcc);
write_data(0xBE); //读取温度
templ=read_data();
temph=read_data();
temp = (temph<<8)|templ;
wendu=temp*0.625+0.5; // 温度扩大10倍,四舍五入
temp=wendu/10;
return temp;
}
void STC_init(){
P1=0x00;//关闭led
led = 0;
wei = duan = 0;
}
void display(uchar weil, uchar duanl, bit dp){
wei=1;
P0=mazhi_wei[weil-1];
wei=duan=dp;
if(dp==1)
P0=(mazhi_duan[duanl]|0x80);
else
P0 = mazhi_duan[duanl];
duan = 0;
}
void main(){
uchar i;
uint wendu;
STC_init();
wendu=readtemp();
delayl(500);
wendu=readtemp();
delayl(500);
while(1) {
wendu = readtemp();
for(i=0; i<80; i++){
display(1,wendu/10, 0);
delayl(3);
display(2, (wendu%10)/1 , 1);
delayl(3);
display(3, wendu % 10, 0);
delayl(3);
}
}
}
```
这段代码实现了基于89C52单片机和DS18B20温度传感器的温湿度显示系统。首先定义了数码管段选表与位选表,初始化单片机及