DS18B20驱动程序
时间: 2023-08-24 11:07:10 浏览: 109
DS18B20是一种数字温度传感器,它使用1线数字接口进行通信。以下是一个简单的DS18B20驱动程序示例,使用C语言编写:
```
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <wiringPi.h>
#define MAX_TIMING 85
int pin = 7;
int read_dht11_dat()
{
uint8_t data[5] = {0, 0, 0, 0, 0};
uint8_t last_state = HIGH;
uint8_t counter = 0;
uint8_t j = 0, i;
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);
delay(18);
digitalWrite(pin, HIGH);
delayMicroseconds(40);
pinMode(pin, INPUT);
for (i = 0; i < MAX_TIMING; i++)
{
counter = 0;
while (digitalRead(pin) == last_state)
{
counter++;
delayMicroseconds(1);
if (counter == 255)
{
break;
}
}
last_state = digitalRead(pin);
if (counter == 255)
break;
if ((i >= 4) && (i % 2 == 0))
{
data[j / 8] <<= 1;
if (counter > 16)
data[j / 8] |= 1;
j++;
}
}
if ((j >= 40) && (data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF)))
{
float temp = ((data[2] & 0x7F) << 8 | data[3]) / 10.0;
if (data[2] & 0x80)
{
temp *= -1;
}
printf("Temperature = %.1f °C\n", temp);
return 0;
}
else
{
printf("Data not good, skip\n");
return -1;
}
}
int main()
{
if (wiringPiSetup() == -1)
exit(1);
while (1)
{
read_dht11_dat();
delay(1000);
}
return 0;
}
```
这个程序使用WiringPi库来控制GPIO引脚。它通过DS18B20传感器读取温度数据,并将其打印到终端上。该程序应该能够在树莓派和其他基于Linux的嵌入式设备上运行。
阅读全文