在物联网和嵌入式系统开发领域,Arduino 是一款广受欢迎的开源电子原型平台,它具有简单易用、成本低廉等优点。而 MPU6050 是一款集成了三轴加速度计和三轴陀螺仪的传感器,能够测量物体的运动和姿态信息。本文将详细介绍如何使用 Arduino 与 MPU6050 传感器进行通信,实现传感器数据的采集与处理,同时还会实现一个 LED 定时闪烁的功能,以展示 Arduino 的多任务处理能力。
硬件准备
- Arduino 开发板(如 Arduino Uno)
- MPU6050 传感器模块
- 超声波测距模块(可选,代码中使用了超声波测距相关引脚定义)
- LED 灯
- 杜邦线若干
https://github.com/fishros/MPU6050_lighthttps://github.com/fishros/MPU6050_light
FishBot主控板原理图开源分享! | 鱼香ROS
#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 2
unsigned 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, SCL
byte 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 accelero
Serial.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;
}