防水的18b20c语言编程,温度传感器18B20驱动程序(C语言)
时间: 2023-10-30 13:06:03 浏览: 39
以下是18B20温度传感器的C语言驱动程序:
```c
#include <stdio.h>
#include <wiringPi.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_c = (float)dht11_dat[2] + (float)(dht11_dat[3] & 0x7F) * 0.1;
if (dht11_dat[3] & 0x80)
temp_c = -temp_c;
printf("Temperature = %.1f Celsius\n", temp_c);
}
else
{
printf("Data not good, skip\n");
}
}
int main()
{
if (wiringPiSetup() == -1)
return 1;
while (1)
{
read_dht11_dat();
delay(1000);
}
return 0;
}
```
这个程序使用了WiringPi库来操作GPIO,因此需要在编译时加上-lwiringPi选项。编译命令如下:
```
gcc -o dht11 dht11.c -lwiringPi
```
这个程序会不断地读取18B20温度传感器的数据,并将温度打印出来。注意,这个程序仅适用于单个传感器,如果需要同时读取多个传感器,需要修改程序。