ESP32-S3 IDF编程第三课:按钮输入
上面一个课程我们介绍了如何去点亮LED,这一节课我们来讲如何利用按钮之类的输入工具,输入信号到esp32
首先,我们一般的4个引脚的按钮是长这样的

如何快速接入呢?很简单,对角线接就行了
那么,怎么接呢?也很简单,一端接3.3v,一端接入对应的引脚即可
那么,代码与上一课大体上一样,只是稍有改动
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
#include <stdio.h> #include <inttypes.h> #include "sdkconfig.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_chip_info.h" #include "esp_flash.h" #include "esp_system.h" #include "driver/gpio.h" void app_main(void) { gpio_config_t io_conf = { .intr_type = GPIO_INTR_DISABLE, .mode = GPIO_MODE_INPUT, .pin_bit_mask = (1ULL << 2), .pull_down_en = 0, .pull_up_en = 0 }; gpio_config(&io_conf); while(1){ if (gpio_get_level(2) == 1) { printf("Button Pressed\n"); } vTaskDelay(pdMS_TO_TICKS(50)); } }
|
可以看到我们这里用了输入GPIO_MODE_INPUT功能这个也很简单
然后,我们这次用了轮询机制,来简单读取按钮
gpio_get_level就是读取引脚,输出1或者0,1是高电平,0是低电平
然后设置延时防止高占用
最后编译一下就可以了
