如何使用 mpu6050 和 arduino uno 来控制立方体,以便立方体随鼠标位置移动?



当我第一次用mpu6050尝试arduino代码时,串行监视器显示了读数。但是,当我尝试将其与 Unity 连接时,读数无法在 Unity 中显示或使用。我被困在这个问题上。我试图使我在 Unity 中创建的立方体随着鼠标位置移动,然后被 mpu 6050 取代。

Arduino 代码

#include <Wire.h>
#include <I2Cdev.h>
#include <MPU6050.h>
MPU6050 mpu;
int16_t ax, ay, az, gx, gy, gz;
int vx, vy;
void setup() {
Serial.begin(115200);
Wire.begin();
mpu.initialize();
//if (!mpu.testConnection()) { while (1); }
}
void loop() {
mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
vx = ((gx+300)/150)-1;  // "+300" because the x axis of gyroscope give 
values about -350 while it's not moving. Change this value if you get 
something different using the TEST code, chacking if there are values far 
from zero.
vy = -(gz-100)/150; // same here about "-100"
String output = String(gx) + ";" + String(gz) + ";" + String(vx) + ";" + 
String(vy);
Serial.println(output);
Serial.flush();
delay(10);
}

统一代码

public class Cube : MonoBehaviour {
SerialPort stream = new SerialPort("COM4", 115200);
public Camera cam;
public float mousex;
public float mousey;
public GameObject target; // is the gameobject to
public float acc_normalizer_factor = 0.00025f;
public float gyro_normalizer_factor = 1.0f / 32768.0f;   // 32768 is max 
value captured during test on imu
//float curr_angle_x = 0;
//float curr_angle_y = 0;
//float curr_angle_z = 0;
float curr_offset_x = 0;
float curr_offset_y = -2;

void Start()
{
stream.Open();

cam = Camera.main;

}
void Update()
{
string dataString = "null received";
dataString = stream.ReadLine();
char splitChar = ';';
string[] dataRaw = dataString.Split(splitChar);
float vx = int.Parse(dataRaw[2]);
float vy = int.Parse(dataRaw[3]);
curr_offset_x += (vx * acc_normalizer_factor);
curr_offset_y += (vy * acc_normalizer_factor);
//get mouse possition
mousex = (curr_offset_x);
mousey = (curr_offset_y);
//adapt it to screen
// 5 in z to be in the front of the camera, but up to you, just 
avoid 0
Vector3 mouseposition = cam.ScreenToWorldPoint(new Vector3(mousex, 
mousey, 5));
//make your gameobject fallow your input
target.transform.position = mouseposition;
}

首先,检查您的设备。数据是否由您的设备发送并由 mpu 连接到的计算机接收? 您也可以尝试在dataString = stream.ReadLine();代码后立即在 Unity 中Debug.Log(dataString)(仅当设备连接到的计算机接收来自 mpu 的数据时才有意义(。

最新更新