在ESPIDF中使用Arduino

官方就有Arduino的组件Arduino 作为 ESP-IDF 组件——Arduino ESP32 最新文档 — Arduino as an ESP-IDF component - - — Arduino ESP32 latest documentation
快速上手

1
idf.py create-project-from-example "espressif/arduino-esp32^3.3.6:hello_world"

添加依赖

1
idf.py add-dependency "espressif/arduino-esp32^3.3.6"

注意,一定要先configTICK_RATE_HZ = 1000,不然会报错,并且无法通过menuconfig修改

配置

更改主程序后缀

把main.c改成main.cpp,注意检查一下CMakeLists.txt文件。

添加依赖库

例如u8g2

  • 新建一个components目录
  • git clone下来 git clone https://github.com/olikraus/u8g2.git
  • components/u8g2/新建CMakeLists.txt
1
2
3
4
5
6
7
8
# 告诉 IDF 扫描这个目录下的所有源文件
file(GLOB_RECURSE SOURCES "cppsrc/*.cpp" "csrc/*.c")

idf_component_register(
SRCS ${SOURCES}
INCLUDE_DIRS "cppsrc" "csrc"
REQUIRES arduino-esp32 # 必须依赖 arduino 组件
)
  • main.c 改名为 main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include "Arduino.h"
#include <U8g2lib.h>

// 4针 I2C 构造
U8G2_SSD1306_128X64_NONAME_F_SW_I2C u8g2(U8G2_R0, /*scl=*/11, /*sda=*/12);
// NONAME无品牌,F帧缓冲模式(Framebuffer Mode),SW软件I2C

extern "C" void app_main() {
initArduino();

u8g2.begin();
u8g2.clearBuffer();
u8g2.setFont(u8g2_font_ncenB08_tr);
u8g2.drawStr(0, 20, "Hello Arduino Lib!");
u8g2.sendBuffer();
}
  • 别忘了ESP-IDF要在/main/CMakeLists.txt中引用依赖
1
2
3
idf_component_register(SRCS "main.cpp"
                    INCLUDE_DIRS "."
                    REQUIRES arduino-esp32 u8g2)

常用库推荐

DHT* 温湿度传感器

1

OLED U8g2 显示屏

1
https://github.com/olikraus/u8g2.git

WS2812 - start

1
2
3
https://github.com/FastLED/FastLED.git

https://github.com/adafruit/Adafruit_NeoPixel.git

常用库使用

FastLED

下载

1
git clone https://github.com/FastLED/FastLED.git components/FastLED

引用库,这个库兼容比较好,已经配置好了自身的CMakeLists.txt文件,只需要在主程序中引用就好了

快速上手

1
2
3
4
5
6
7
8
9
10
11
12
#include <FastLED.h>
#define NUM_LEDS 60
CRGB leds[NUM_LEDS];

void setup() {
FastLED.addLeds<WS2812, 6>(leds, NUM_LEDS);
}

void loop() {
leds[0] = CRGB::Red; FastLED.show(); delay(500);
leds[0] = CRGB::Blue; FastLED.show(); delay(500);
}

Adafruit_NeoPixel

下载安装

1
git clone https://github.com/adafruit/Adafruit_NeoPixel.git components/Adafruit_NeoPixel

配置CMake

1
2
3
4
5
6
7
8
# 告诉 IDF 扫描这个目录下的所有源文件
file(GLOB_RECURSE SOURCES "*.cpp" "*.c")

idf_component_register(
    SRCS ${SOURCES}
    INCLUDE_DIRS "."
    REQUIRES arduino-esp32
)

踩坑

保存构建的日志

1
idf.py build 2>&1 | Tee-Object -FilePath "build_log.txt"

方案一

  • 运行 idf.py menuconfig
  • 依次进入路径: Arduino Configuration —> Debug Log Configuration
  • 找到并勾选: [*] Forward ESP-IDF logging to Serial (对应宏 CONFIG_ARDUHAL_ESP_LOG)
  • 保存并退出。

方案二

1
2
3
4
5
6
7
8
9
10
11
// 强制先包含 Arduino.h 以确保宏定义正确覆盖
#include "Arduino.h"
#include "esp_log.h" // 显式包含 IDF 日志头文件
#include <WiFi.h>

// ... 其余代码不变
// 最后面添加
extern "C" {
void __wrap_esp_log_write(esp_log_level_t level, const char *tag, const char *format, ...) {}
void __wrap_esp_log_writev(esp_log_level_t level, const char *tag, const char *format, va_list args) {}
}