Internet of Things Projects with ESP32
上QQ阅读APP看书,第一时间看更新

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.