1、在项目文件夹中新建文件夹 components
2、进入该文件夹 打开终端输入
sudo git clone https://github.com/natanaeljr/esp32-I2Cbus.git I2Cbus
sudo git clone https://github.com/natanaeljr/esp32-MPU-driver.git MPUdriver
sudo chmod -R 777 *
3、在vs code 终端中输入
idf.py menuconfig
输入 S 保存配置
4、修改 main.c 文件名为main.cpp,在文件中 main函数前增加 extern "C"
5、根据模板例子填入代码
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include "driver/gpio.h"
#include "driver/i2c.h"
#include "esp_err.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/portmacro.h"
#include "freertos/task.h"
#include "sdkconfig.h"
#include "I2Cbus.hpp"
#include "MPU.hpp"
#include "mpu/math.hpp"
#include "mpu/types.hpp"
static const char *TAG = "example";
static constexpr gpio_num_t SDA = GPIO_NUM_20;
static constexpr gpio_num_t SCL = GPIO_NUM_21;
static constexpr uint32_t CLOCK_SPEED = 400000;
extern "C" void app_main(void)
{
fflush(stdout);
i2c0.begin(SDA, SCL, CLOCK_SPEED);
MPU_t MPU; // create a default MPU object
MPU.setBus(i2c0); // set bus port, not really needed since default is i2c0
MPU.setAddr(mpud::MPU_I2CADDRESS_AD0_LOW);
while (esp_err_t err = MPU.testConnection())
{
ESP_LOGE(TAG, "Failed to connect to the MPU, error=%#X", err);
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
ESP_LOGI(TAG, "MPU connection successful!");
ESP_ERROR_CHECK(MPU.initialize());
printf("Reading sensor data:\n");
mpud::raw_axes_t accelRaw;
mpud::raw_axes_t gyroRaw;
mpud::float_axes_t accelG;
mpud::float_axes_t gyroDPS;
while (true)
{
MPU.acceleration(&accelRaw);
MPU.rotation(&gyroRaw);
accelG = mpud::accelGravity(accelRaw, mpud::ACCEL_FS_4G);
gyroDPS = mpud::gyroDegPerSec(gyroRaw, mpud::GYRO_FS_500DPS);
printf("accel: [%+6.2f %+6.2f %+6.2f ] (G) \t", accelG.x, accelG.y, accelG.z);
printf("gyro: [%+7.2f %+7.2f %+7.2f ] (º/s)\n", gyroDPS[0], gyroDPS[1], gyroDPS[2]);
vTaskDelay(100 / portTICK_PERIOD_MS);
}
}
上传运行后