Button Driver

When using ESP32-C3-DevKitM-1 to simulate smart light for development, we can find two buttons on the board, namely the Boot button and the RST button. The RST button is used for resetting and restarting ESP32-C3, while the Boot button functions as a regular button once the firmware starts operating. In other words, the Boot button can be used to simulate a light switch.

For this purpose, we introduce the button component as the button driver. You may read the source code to learn about its development, as we will not expound on it in this book. To add the driver to the smart light project, please follow the steps below.

Create a folder named components under the directory of the smart light project and put the components used by the project into the folder.

Create a subfolder named button under components.

Then, create the source files and header files for the button driver in button, and edit the code accordingly.

Specific code can be found from book-esp32c3-iot-projects/device_firmware/components/button.

In the main folder of the project, create a source file named app_driver.c to process all the drivers. Meanwhile, create header files in the include folder under main. Add driver operations and function declarations to corresponding files, such as driver initialization and button event processing. The key code is as follows.

//Callback function for pressing the button
static void push_btn_cb(void *arg)
{
    //Code Omitted
}
void app_driver_init()
{
    //Initializing button driver
    button_config_t btn_cfg = {
        .type = BUTTON_TYPE_GPIO,
        .gpio_button_config = {
            .gpio_num     = LIGHT_BUTTON_GPIO,
            .active_level = LIGHT_BUTTON_ACTIVE_LEVEL,
        },
    };
    button_handle_t btn_handle = iot_button_create(&btn_cfg);
    if (btn_handle) {
        iot_button_register_cb(btn_handle, BUTTON_PRESS_UP, push_btn_cb);
    }
    //Code Omitted
}

2. Adding source files to the compiling system

First, edit the CMakeLists.txt file under the project directory. Append the path of the components in components to the search path with the following code:

//Code Omitted
set(EXTRA_COMPONENT_DIRS ${CMAKE_CURRENT_LIST_DIR}/../components)   
//Code Omitted`

Then, edit the CMakeLists.txt file in the main folder. Add the source file app_driver.c to the compiling system with the following code:

set(srcs "app_main.c"
        "app_driver.c")
set(include_dirs "include")
idf_component_register(SRCS "${srcs}"
                    INCLUDE_DIRS "${include_dirs}")

Besides, the button component also has a CMakeLists.txt file, which is used to add the button driver source code to the compiling system. You may refer to book-esp32c3-iot-projects/device_firmware/components/button/CMakeLists.txt for details. Other components to be added have similar structures and will not be explained again in subsequent chapters.