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

Writing the program

Now, we write scripts and codes on the Makefile, component.mk, and blinking.c files:

  1. In the Makefile file, we declare our project name. This should be the same name as the project folder. The following are Makefile scripts:
   PROJECT_NAME := blinking

include $(IDF_PATH)/make/project.mk

  1. component.mk is required for compiling purposes. You should create a component file with this exact name. The content of the component.mk file is empty:
    #
# "main" pseudo-component makefile.
#
# (Uses default behavior of compiling all source files in
directory, adding 'include' to include path.)
  1. Now, we write code for our main program, blinking.c. Firstly, we declare our required library headers as follows:
    #include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "sdkconfig.h"
  1. We define our three LEDs on ESP32 GPIO. We use IO12, IO14, and IO26 pins from ESP32 GPIO:
    #define LED1 12
#define LED2 14
#define LED3 26
  1. A main entry of the program is app_main(). For this, we create a task and pass a function, called blinking_task:
    void app_main()
{
xTaskCreate(&blinking_task, "blinking_task",
configMINIMAL_STACK_SIZE, NULL, 5, NULL);
}
  1. The blinking_task() function performs GPIO initialization by calling gpio_pad_select_gpio(). Then, we set the GPIO pin as output using the gpio_set_direction() function. In the main loop, we turn on the LEDs one by one. We call the turn_on_led() function to perform this task:
void blinking_task(void *pvParameter)
{
// set gpio and its direction
gpio_pad_select_gpio(LED1);
gpio_set_direction(LED1, GPIO_MODE_OUTPUT);
gpio_pad_select_gpio(LED2);
gpio_set_direction(LED2, GPIO_MODE_OUTPUT);
gpio_pad_select_gpio(LED3);
gpio_set_direction(LED3, GPIO_MODE_OUTPUT);

int current_led = 1;
while(1) {
turn_on_led(current_led);
vTaskDelay(1000 / portTICK_PERIOD_MS);

current_led++;
if(current_led>3)
current_led = 1;
}
}
  1. To turn on/off LEDs, we call gpio_set_level() with 1 or 0 parameters. If we pass 1 on gpio_set_level(), it means we set a power voltage on that GPIO:
void turn_on_led(int led)
{
// turn off all leds
gpio_set_level(LED1, 0);
gpio_set_level(LED2, 0);
gpio_set_level(LED3, 0);

switch(led)
{
case 1:
gpio_set_level(LED1, 1);
break;
case 2:
gpio_set_level(LED2, 1);
break;
case 3:
gpio_set_level(LED3, 1);
break;
}
}
  1. Now, save all programs.

Next, we configure the project before flashing on the ESP32 board.