- Internet of Things Projects with ESP32
- Agus Kurniawan
- 331字
- 2021-06-24 16:02:51
Writing the program
Now, we write scripts and codes on the Makefile, component.mk, and blinking.c files:
- 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
- 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.)
- 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"
- 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
- 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);
}
- 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;
}
}
- 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;
}
}
- Now, save all programs.
Next, we configure the project before flashing on the ESP32 board.
推薦閱讀
- 24小時學會電腦組裝與維護
- 龍芯應用開發標準教程
- 電腦組裝與維修從入門到精通(第2版)
- 精選單片機設計與制作30例(第2版)
- Manage Partitions with GParted How-to
- 計算機維修與維護技術速成
- Svelte 3 Up and Running
- 計算機組裝與維護(第3版)
- Practical Machine Learning with R
- 筆記本電腦應用技巧
- Creating Flat Design Websites
- 計算機組裝維修與外設配置(高等職業院校教改示范教材·計算機系列)
- Source SDK Game Development Essentials
- 單片機開發與典型工程項目實例詳解
- 基于PROTEUS的電路設計、仿真與制板