使用DS18B20采集温度,并将其显示,精确到一位小数,用c语言
时间: 2024-05-11 19:16:34 浏览: 8
来实现该功能的程序该怎么写?
答:你可以尝试使用以下代码来实现此功能:
```
#include <stdio.h>
#include <stdlib.h>
#include <wiringPi.h>
#include <linux/spi/spidev.h>
#include <unistd.h>
#include <stdint.h>
#define MAXTIMINGS 85
#define DHTPIN 7
int dht11_dat[5] = { 0, 0, 0, 0, 0 };
void read_dht11_dat()
{
uint8_t laststate = HIGH;
uint8_t counter = 0;
uint8_t j = 0, i;
dht11_dat[0] = dht11_dat[1] = dht11_dat[2] = dht11_dat[3] = dht11_dat[4] = 0;
pinMode(DHTPIN, OUTPUT);
digitalWrite(DHTPIN, LOW);
delay(18);
digitalWrite(DHTPIN, HIGH);
delayMicroseconds(40);
pinMode(DHTPIN, INPUT);
for (i = 0; i < MAXTIMINGS; i++) {
counter = 0;
while (digitalRead(DHTPIN) == laststate) {
counter++;
delayMicroseconds(1);
if (counter == 255) {
break;
}
}
laststate = digitalRead(DHTPIN);
if (counter == 255) {
break;
}
if ((i >= 4) && (i % 2 == 0)) {
dht11_dat[j / 8] <<= 1;
if (counter > 16) {
dht11_dat[j / 8] |= 1;
}
j++;
}
}
if ((j >= 40) && (dht11_dat[4] == ((dht11_dat[0] + dht11_dat[1] + dht11_dat[2] + dht11_dat[3]) & 0xFF))) {
float temp = ((float)dht11_dat[2] * 9.0 / 5.0) + 32.0;
printf("Temperature: %.1f F\n", temp);
} else {
printf("Data not good, skip\n");
}
}
int main(void)
{
if (wiringPiSetup() == -1){
exit(1);
}
printf("Raspberry Pi wiringPi DHT11 Temperature test program\n\n");
while (1) {
read_dht11_dat();
delay(1000);
}
return 0;
}
```
在此代码中,我们使用 DS18B20 温度传感器来读取温度值,并将其转换为华氏温度值。首先,我们需要读取传感器的数据。在 main 函数中,我们使用了一个无限循环,每隔一秒钟读取一次温度传感器。在 read_dht11_dat 函数中,我们使用WiringPi 库来设置传感器引脚模式和读取传感器数据。最后,我们计算温度值并输出到终端。