MPU6050 六轴姿态 Arduino ESP32 Test
在物联网和嵌入式系统开发领域,Arduino 是一款广受欢迎的开源电子原型平台,它具有简单易用、成本低廉等优点。而 MPU6050 是一款集成了三轴加速度计和三轴陀螺仪的传感器,能够测量物体的运动和姿态信息。本文将详细介绍如何使用 Arduino 与 MPU6050 传感器进行通信,实现传感器数据的采集与处理,同时还会实现一个 LED 定时闪烁的功能,以展示 Arduino 的多任务处理能力。
硬件准备
- Arduino 开发板(如 Arduino Uno)
- MPU6050 传感器模块
- 超声波测距模块(可选,代码中使用了超声波测距相关引脚定义)
- LED 灯
- 杜邦线若干
https://github.com/fishros/MPU6050_lighthttps://github.com/fishros/MPU6050_light
FishBot主控板原理图开源分享! | 鱼香ROS
FishBot主控板原理图开源分享! | 鱼香ROShttps://fishros.org.cn/forum/topic/894/fishbot%E4%B8%BB%E6%8E%A7%E6%9D%BF%E5%8E%9F%E7%90%86%E5%9B%BE%E5%BC%80%E6%BA%90%E5%88%86%E4%BA%AB
#include <Arduino.h>
#include <Wire.h>
#include <MPU6050_light.h>MPU6050 mpu(Wire);
// put function declarations here:
int myFunction(int, int);#define TRIG 27
#define ECHO 21
#define LED_BUILTIN 2unsigned long previousMillis = 0; // 用于记录上一次电平切换的时间
const long interval = 500; // 定时器间隔,单位为毫秒void setup() {// put your setup code here, to run once:int result = myFunction(2, 3);Serial.begin(115200);pinMode(TRIG, OUTPUT);pinMode(ECHO, INPUT);pinMode(LED_BUILTIN, OUTPUT);Wire.begin(18,19); // SDA, SCLbyte status = mpu.begin();Serial.print(F("MPU6050 status: "));Serial.println(status);while(status != 0) {// stop everything if could not connect to MPU6050}mpu.calcOffsets(true, true); // gyro and acceleroSerial.println("Done!\n");}unsigned long timer = 0;
void loop() {// put your main code here, to run repeatedly:digitalWrite(TRIG, HIGH);delayMicroseconds(10);digitalWrite(TRIG, LOW);double duration = pulseIn(ECHO, HIGH);double distance = duration * 0.034 / 2;//Serial.printf("Distance: %lf cm\n", distance);mpu.update();if((millis()-timer)>1000){// 温度Serial.printf("Temp: %lf\n", mpu.getTemp());// 加速度计数据Serial.printf("Accel: %lf %lf %lf\n", mpu.getAccX(), mpu.getAccY(), mpu.getAccZ());// 加速度计角度Serial.printf("Angle: %lf %lf %lf\n", mpu.getAngleX(), mpu.getAngleY(), mpu.getAngleZ());// 陀螺仪数据Serial.printf("Gyro: %lf %lf %lf\n", mpu.getGyroX(), mpu.getGyroY(), mpu.getGyroZ());// 综合角度Serial.printf("Angle: %lf %lf %lf\n", mpu.getAngleX(), mpu.getAngleY(), mpu.getAngleZ());Serial.println("===========================\n");timer = millis();}// 获取当前时间unsigned long currentMillis = millis();// 检查是否达到定时器间隔if (currentMillis - previousMillis >= interval) {// 记录当前时间previousMillis = currentMillis;// 切换2号脚的电平digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));}
}// put function definitions here:
int myFunction(int x, int y) {return x + y;
}