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

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.

主站蜘蛛池模板: 拜城县| 巩义市| 邻水| 湾仔区| 长海县| 本溪市| 龙海市| 泗洪县| 富阳市| 霍林郭勒市| 慈利县| 武平县| 石家庄市| 塘沽区| 海口市| 四子王旗| 南溪县| 淮阳县| 四子王旗| 鸡东县| 治多县| 北流市| 吕梁市| 盐津县| 牙克石市| 岳普湖县| 宜章县| 海原县| 玉田县| 福安市| 岳阳县| 金川县| 西宁市| 汤阴县| 华安县| 昌乐县| 会泽县| 陕西省| 霞浦县| 连平县| 合阳县|