用C写一个单片机测量当前室内温度,,测量数据保留一位小数,数据用两种格式显示,当温度高于设定值时,LED每隔一秒闪烁,共三秒
时间: 2023-04-04 09:03:56 浏览: 41
您好,我可以回答您的问题。以下是代码示例:
#include <reg52.h>
#include <stdio.h>
sbit LED = P1^0; // LED连接的IO口
sbit DQ = P3^7; // DS18B20连接的IO口
unsigned char code table[] = { // 数码管显示表
0x3f, 0x06, 0x5b, 0x4f, 0x66,
0x6d, 0x7d, 0x07, 0x7f, 0x6f
};
void delay(unsigned int i) { // 延时函数
while(i--);
}
void init_ds18b20() { // 初始化DS18B20
unsigned char i;
DQ = 1;
delay(5);
DQ = 0;
delay(500);
DQ = 1;
delay(50);
i = DQ;
delay(500);
}
void write_ds18b20(unsigned char dat) { // 写入一个字节
unsigned char i;
for(i=0; i<8; i++) {
DQ = 0;
DQ = dat & 0x01;
delay(5);
DQ = 1;
dat >>= 1;
}
}
unsigned char read_ds18b20() { // 读取一个字节
unsigned char i, dat = 0;
for(i=0; i<8; i++) {
DQ = 0;
dat >>= 1;
DQ = 1;
if(DQ) dat |= 0x80;
delay(5);
}
return dat;
}
void start_ds18b20() { // 启动温度转换
init_ds18b20();
write_ds18b20(0xcc);
write_ds18b20(0x44);
}
int read_temperature() { // 读取温度值
unsigned char tl, th;
int temp;
init_ds18b20();
write_ds18b20(0xcc);
write_ds18b20(0xbe);
tl = read_ds18b20();
th = read_ds18b20();
temp = th;
temp <<= 8;
temp |= tl;
return temp;
}
void display_temperature(int temp) { // 显示温度值
unsigned char i, j, k;
unsigned char code disp[] = { // 数码管连接的IO口
0xfe, 0xfd, 0xfb, 0xf7
};
unsigned char buf[4];
sprintf(buf, "%.1f", temp / 16.0);
for(i=0; i<4; i++) {
j = buf[i] - '0';
k = table[j];
P2 = disp[i];
P0 = k;
delay(100);
}
}
void main() {
int temp, set_temp = 25;
unsigned char i;
while(1) {
start_ds18b20();
temp = read_temperature();
display_temperature(temp);
if(temp > set_temp * 16) { // 温度高于设定值
for(i=0; i<6; i++) { // LED闪烁3秒
LED = ~LED;
delay(500);
}
}
}
}
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)