官术网_书友最值得收藏!

Building a program

Building a program for ESP32 is a multi-step process. Let's look at each step and begin our build for the weather monitoring system:

  1. Create a project called dhtdemo. Please read Chapter 1, Getting Started with ESP32, which describes how to create an X project. Our main program is the dhtdemo.c file. 
  2. To access the DHT22 sensor, we can use the DHT library from the ESP-IDF component libraries: https://github.com/UncleRus/esp-idf-lib. This project consists of some drivers for sensor and actuator devices that are compatible with the ESP32 chip/board. You can use these drivers for your own projects. In this section, we use the dht driver to enable working with the DHT sensor device.
  1. Copy the dht components folder from the esp-idf-lib project into your local esp-idf/components folder. You can see that my dht component has been copied in Figure 2-5:
Figure 2-5: Adding the dht component on ESP-IDF
  1. Now, we will write our program on the dhtdemo.c file. Firstly, we define our required libraries for our ESP32 board. The header files that will be loaded in our program are as follows:
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "sdkconfig.h"
  1. We declare the dht.h header to access the DHT library. We also define our DHT model as DHT_TYPE_DHT22. Lastly, we set GPIO 26 for the DHT22 sensor module:
#include <dht.h>
static const dht_sensor_type_t sensor_type = DHT_TYPE_DHT22;
static const gpio_num_t dht_gpio = 26;
  1. Now, we will write the main entry program, app_main(). We create a task by calling the dht_task() function. Then, we call the dht_task() function using xTaskCreate():
void app_main()
{
xTaskCreate(&dht_task, "dht_task", configMINIMAL_STACK_SIZE, NULL, 5, NULL);
}

In the dht_task() function, we read the temperature and humidity from DHT22 using the dht_read_data() function. The results of the reading sensor are stored in two variables: temperature and humidity. These sensor values will then be printed on the Terminal using printf().

This program will read sensor data every five seconds. You can write this complete program for the dht_task() function as follows:

void dht_task(void *pvParameter)
{
int16_t temperature = 0;
int16_t humidity = 0;

while(1) {
if (dht_read_data(sensor_type, dht_gpio, &humidity, &temperature) == ESP_OK)
printf("Humidity: %d%% Temp: %d^C\n", humidity / 10, temperature / 10);
else
printf("Could not read data from sensor\n");

vTaskDelay(5000 / portTICK_PERIOD_MS);

}
}

Save all codes in the dhtdemo.c file and then compile and flash to the ESP32 board.

主站蜘蛛池模板: 和田市| 佳木斯市| 长治县| 内江市| 呼图壁县| 建阳市| 蓬溪县| 平山县| 北京市| 怀仁县| 永安市| 开化县| 诸暨市| 谷城县| 信丰县| 泉州市| 诸暨市| 古交市| 新竹市| 永康市| 泽普县| 永新县| 安图县| 阜康市| 垫江县| 密山市| 东莞市| 双辽市| 定日县| 江源县| 麻城市| 安康市| 肥东县| 旺苍县| 江都市| 合山市| 武乡县| 延寿县| 上饶市| 北流市| 商洛市|