TA的每日心情 | 奋斗 前天 11:38 |
---|
签到天数: 19 天 连续签到: 1 天 [LV.4]偶尔看看III
|
本帖最后由 dirty123 于 2024-4-14 09:55 编辑
树莓派5有多种方式读取使用传感器,本篇讲述使用WiringPi 库,编写C语言代码,驱动实现对DHT11传感器温湿度的读取。
一.环境、硬件准备
1.安装 WiringPi:
①系统更新sudo apt-get update②这里需要使用到WiringPi库,通过git克隆.通过git --version查询安装及版本,若没安装如下安装git
sudo apt-get install git-core
③接着下载 wiringPi库,如下
git clone https://github.com/WiringPi/WiringPi
④编译安装 wiringPi
cd WiringPi
sudo ./build
图1:WiringPi安装
2.安装好WiringPi后,命令gpio readall查询开发板WiringPi引脚编号对应情况,这里选择7脚作为与DHT11的数据通讯引脚
图2:引脚编号
3.开发板接好DHT11传感器
图3:开发板接好DHT11传感器
二.代码编写编译运行
1.编写dht11.c代码如下
- #include <wiringPi.h>
- #include <stdio.h>
- #include <stdlib.h>
- typedef unsigned char uint8;
- typedef unsigned int uint16;
- typedef unsigned long uint32;
- #define HIGH_TIME 32
- int pinNumber = 7;
- uint32 databuf;
- uint8 readSensorData(void)
- {
- uint8 crc;
- uint8 i;
-
- pinMode(pinNumber, OUTPUT); // set mode to output
- digitalWrite(pinNumber, 0); // output a high level
- delay(25);
- digitalWrite(pinNumber, 1); // output a low level
- pinMode(pinNumber, INPUT); // set mode to input
- pullUpDnControl(pinNumber, PUD_UP);
-
- delayMicroseconds(27);
- if (digitalRead(pinNumber) == 0) //SENSOR ANS
- {
- while (!digitalRead(pinNumber))
- ; //wait to high
-
- for (i = 0; i < 32; i++)
- {
- while (digitalRead(pinNumber))
- ; //data clock start
- while (!digitalRead(pinNumber))
- ; //data start
- delayMicroseconds(HIGH_TIME);
- databuf *= 2;
- if (digitalRead(pinNumber) == 1) //1
- {
- databuf++;
- }
- }
-
- for (i = 0; i < 8; i++)
- {
- while (digitalRead(pinNumber))
- ; //data clock start
- while (!digitalRead(pinNumber))
- ; //data start
- delayMicroseconds(HIGH_TIME);
- crc *= 2;
- if (digitalRead(pinNumber) == 1) //1
- {
- crc++;
- }
- }
- return 1;
- }
- else
- {
- return 0;
- }
- }
-
- int main(void)
- {
- printf("PIN:%d\n", pinNumber);
-
- if (-1 == wiringPiSetup()) {
- printf("Setup wiringPi failed!");
- return 1;
- }
-
- pinMode(pinNumber, OUTPUT); // set mode to output
- digitalWrite(pinNumber, 1); // output a high level
-
- printf("Starting...\n");
- while (1)
- {
- pinMode(pinNumber, OUTPUT); // set mode to output
- digitalWrite(pinNumber, 1); // output a high level
- delay(3000);
- if (readSensorData())
- {
- printf("Sensor data read ok!\n");
- printf("RH:%d.%d\n", (databuf >> 24) & 0xff, (databuf >> 16) & 0xff);
- printf("TMP:%d.%d\n", (databuf >> 8) & 0xff, databuf & 0xff);
- databuf = 0;
- }
- else
- {
- printf("Sensor dosent ans!\n");
- databuf = 0;
- }
- }
- return 0;
- }
复制代码 2.编译
gcc -Wall -o dht11 dht11.c -lwiringPi
编译完出现可执行文件如下
图4:编译
3.运行
sudo ./dht11
这时可以看到读出的传感器DHT11的湿度与温度,如下
图5:传感器DHT11的湿度与温度
至此实现对DHT11传感器温湿度的读取。
|
|