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

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.

主站蜘蛛池模板: 民和| 上犹县| 安顺市| 永丰县| 宜春市| 威宁| 锡林郭勒盟| 普宁市| 西乡县| 师宗县| 徐闻县| 舟山市| 榆树市| 新竹市| 江川县| 灌阳县| 铁力市| 宁晋县| 柞水县| 石楼县| 敖汉旗| 麻江县| 广东省| 昌平区| 长葛市| 洱源县| 阿拉善右旗| 仁怀市| 彩票| 长乐市| 临湘市| 白朗县| 太原市| 枞阳县| 定远县| 水富县| 诸城市| 藁城市| 龙海市| 晋宁县| 桐梓县|